这是我运行用Room
和RX java
开发的示例项目之后发生的错误:
e: /home/milad/workspace/android/WalletMVVM/app/build/tmp/kapt3/stubs/debug/com/example/walletmvvm/data/dao/CurrencyDao.java:15: error: Not sure how to handle insert method's return type.
public abstract io.reactivex.Single<com.example.walletmvvm.data.model.CurrencyModel> insert(@org.jetbrains.annotations.NotNull()
我搜索了很多,但没有找到任何东西。
我可以使用Retrofit
来实现RX java
并使用它,并且我可以使用Room
在其他线程中运行RX java
查询,但是我无法设置observer
和subscribe
和observable
一起RX java
。
一切听起来不错
这是我的Dao
:
@Dao
interface CurrencyDao {
@Query("SELECT * FROM ${DbConstants.TABLE_CURRENCY} ORDER BY ${DbConstants.NAME_CURRENCY_MODEL} ASC")
fun getCurrencyList(): Observable<List<CurrencyModel>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(currencyModel: CurrencyModel): Single<CurrencyModel>
}
这是我的repository
:
companion object {
// For Singleton instantiation
@Volatile
private var instance: CurrencyRepository? = null
fun getInstance(currencyDao: CurrencyDao) =
instance ?: synchronized(this) {
instance ?: CurrencyRepository(currencyDao).also { instance = it }
}
}
fun getCurrencyList(): Observable<List<CurrencyModel>>? {
return currencyDao.getCurrencyList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
这是我fragment
我observer
的数据:
@SuppressLint("CheckResult")
private fun initObservers() {
val getCurrencyListObserver = currencyViewModel.getCurrencyLists()
getCurrencyListObserver?.subscribeWith(getCurrenciesFromDatabase())
}
private fun getCurrenciesFromDatabase() : Observer<List<CurrencyModel>> {
return object : Observer<List<CurrencyModel>> {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: List<CurrencyModel>) {
t.let {
showResult(it.size.toString() + " items")
setRecyclerData(it)
binding.listSize = it.size
}
}
override fun onError(e: Throwable) {
}
}
}
我在googlesamples/android-architecture-components中看到了有关Kotlin的示例代码,但它们没有使用观察者
更新:
因为在那之后我删除了single
我不能使用:
currencyDao.insert(currency)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
并且currencyDao.insert(currency)
无法访问.subscribeOn()
和其他
更新:
当我将返回类型更改为Long
类型但遇到新的error
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(currencyModel: CurrencyModel): Single<Long>
新错误是:
e: /home/milad/workspace/android/WalletMVVM/app/build/tmp/kapt3/stubs/debug/com/example/walletmvvm/data/dao/CurrencyDao.java:11: error: Not sure how to convert a Cursor to this method's return type (java.lang.Object).
public abstract io.reactivex.Observable<java.lang.Object> getCurrencyList();
更新:
我将insert
的返回类型更改为Completable
并固定了
答案 0 :(得分:1)
您的:
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(currencyModel: CurrencyModel): Single<CurrencyModel>
应返回Completable
而不是Single
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(currencyModel: CurrencyModel): Completable
那是因为完成操作后无需返回任何内容。它只是在背景中进入onComplete
块。