Executing delete with room (rxjava)

孤者浪人 提交于 2019-12-05 04:08:01
909080

Based on info from this question: Run Void Method in Background (StackOverflow)

Using a Completable and subscribing on another thread like this:

Completable.fromAction(this::clearCachedData)
   .subscribeOn(Schedulers.io())
   .subscribe();

worked for me. clearCachedData method executes the query in Room that I'm calling.

My query is:

/**
 * Delete all data in the items table.
 */
@Query("DELETE FROM items")
void deleteWeatherItems();

I know this is late. But I ran into the same problem and were able to solve it with following

In Dao class

@Query("DELETE FROM users")
    fun deleteAllUser()

Call it like this. This way you can subscribe and it will run in the background.

Single.fromCallable {
        user.deleteAllUser() //User Dao fun
    }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(..do stuff..)

Replace Observable just method to create.

  Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Object> e) throws Exception {
                e.onNext(tileDatabase.getCategoryDeo().deleteCategory(category));

            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull Object o) {
                        Toast.makeText(MainActivity.this, "Record deleted ", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });

Try to pass a list of users to deletion function and return the count of the deleted users (the code is in Kotlin).

@Dao
public interface UserDao {
    ...

    @Delete
    fun deleteUsers(users: List<User>): Int
}

This would be the database class:

@Database(entities = [User::class], version = 1)
abstract class UsersDatabase : RoomDatabase() {

    abstract fun userDao(): UserDao

    companion object {
        private var INSTANCE: UsersDatabase? = null

        fun getInstance(context: Context): UsersDatabase? {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.applicationContext, UsersDatabase::class.java, "my_database.db").build()
            }
            return INSTANCE
        }

        ...
}

And these the repository and the viewModel (Room Android Architecture):

class UsersRepository internal constructor(val application: Application) {

   private val userDao: UserDao = UsersDatabase.getInstance(application)!!.userDao()

   ...

   fun deleteUsers(users: List<User>): Single<Int> {
        return Single.fromCallable { userDao.deleteUsers(users) }
    }
}


class UsersViewModel(val app: Application) : AndroidViewModel(app) {
    private val repo: UsersRepository = UsesRepository(application = app)
    ...

    fun deleteUsers(users: List<User>): Single<Int> {
        return repo.deleteUsers(users).subscribeOn(Schedulers.io())
    }
}

And then in some activity or fragment:

class UsersActivity : AppCompatActivity() {

    private lateinit var viewModel: UsersViewModel
    ...

    override fun onCreate(savedInstanceState: Bundle?) {
    ...
       viewModel = ViewModelProviders.of(this).get(UsersViewModel::class.java)
    }

    fun removeUsers(users: List<User>) {
       ...
       viewModel.deleteUsers(users).subscribe(this::toast)
    }
    ...

    fun toast() {
        Toast.make(this, "Users deleted", Toast.LENGTH_SHORT).show
    }
}
@Query("DELETE FROM User.TABLE_NAME")
public void nukeTable();

@Query("DELETE FROM " + User.TABLE_NAME + " WHERE " + User.COLUMN_ID + " = :id")
int deleteById(long id);

These method could be useful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!