gpt4 book ai didi

android - RxJava 不在后台线程上运行

转载 作者:行者123 更新时间:2023-11-29 16:40:26 26 4
gpt4 key购买 nike

我正在尝试在 Room 中保存数据,它需要一些后台线程来保存数据。所以我创建了一个这样的可观察对象

val obs: Observable<MutableLiveData<List<Source>>>? = Observable.fromCallable(object :Callable<MutableLiveData<List<Source>>>{
override fun call(): MutableLiveData<List<Source>> {

return mutableLiveData
}
})

然后我就这样订阅,观察,退订

obs?.subscribeOn(Schedulers.io())?.observeOn(AndroidSchedulers.mainThread())?.unsubscribeOn(Schedulers.io())
?.subscribe(object : Observer<MutableLiveData<List<Source>>>{
override fun onComplete() {

}

override fun onSubscribe(d: Disposable?) {

}

override fun onNext(value: MutableLiveData<List<Source>>?) {
for(source in value!!.value!!.iterator()){
sourceDao.insert(source)//this is the line number 87, that logcat is pointing
}
}

override fun onError(e: Throwable?) {
e?.printStackTrace()
}
})

我在 Schedulers.io 线程上订阅它,然后在 AndroidSchedulers.mainThread() 上观察它,但我仍然没有收到后台线程错误。更具体地说

    Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
at android.arch.persistence.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:204)
at android.arch.persistence.room.RoomDatabase.beginTransaction(RoomDatabase.java:251)
06-18 11:11:08.674 3732-3732/com.theanilpaudel.technewspro W/System.err: at com.package.myapp.room.SourceDao_Impl.insert(SourceDao_Impl.java:63)
at com.package.myapp.main.MainRepository$saveToRoom$1.onNext(MainRepository.kt:87)
at com.package.myapp.main.MainRepository$saveToRoom$1.onNext(MainRepository.kt:76)

最佳答案

在 Observable 中执行您的数据库操作,而不是在您的观察者中:

val obs: Observable<MutableLiveData<List<Source>>>? = Observable.fromCallable(object :Callable<MutableLiveData<List<Source>>>{
override fun call(): MutableLiveData<List<Source>> {
for(source in mutableLiveData!!.value!!.iterator()){
sourceDao.insert(source)
}
return mutableLiveData
})
.subscribeOn(Schedulers.io())?.observeOn(AndroidSchedulers.mainThread())?.unsubscribeOn(Schedulers.io())
?.subscribe(object : Observer<MutableLiveData<List<Source>>>{
override fun onComplete() {

}

override fun onSubscribe(d: Disposable?) {

}

override fun onNext(value: MutableLiveData<List<Source>>?) {
// Nothing todo right more
}

override fun onError(e: Throwable?) {
e?.printStackTrace()
}
})
})

关于android - RxJava 不在后台线程上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50903138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com