RxJava not running on Background thread - android

I am trying to save data in Room and it requires some background thread to save data. So I have created an observable like this
val obs: Observable<MutableLiveData<List<Source>>>? = Observable.fromCallable(object :Callable<MutableLiveData<List<Source>>>{
override fun call(): MutableLiveData<List<Source>> {
return mutableLiveData
}
})
Then I am subscribing, observing and unsubscribing it like this
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()
}
})
I am subscribing it on the Schedulers.io thread then observing it on the AndroidSchedulers.mainThread() but still I am getting not on background thread error. More specifically
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)

Execute your DB operation within the Observable and not in your Observer:
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()
}
})
})

It makes sense because you have observeOn the main thread and you are doing your work in the observer (observeOn manages the thread of the observer).
To fix this, you can use flatmap on your obs and do the for loop in there. Since flatmap requires you to return an Observable, you can return Observable.just(true) after your for loop.

Related

RxJava BehaviorSubject subcribeoN

Below Code
why onnext called only once? When I remove subscribeOn it was called for every number.
when I subscribeOn io thread just once called (for 8658)
can someone explain it to me?
val subject = BehaviorSubject.create<Int>()
subject.onNext(2121)
subject.distinctUntilChanged().doOnNext {
Log.d("AHMET VEFA SARUHAN", it.toString())
}.subscribeOn(Schedulers.io()).subscribe(object : Observer<Int> {
override fun onSubscribe(d: Disposable?) {
}
override fun onNext(t: Int?) {
}
override fun onError(e: Throwable?) {
}
override fun onComplete() {
}
})
subject.onNext(5436)
subject.onNext(8658)
By using subscribeOn, the chain to observe the BehaviorSubject is established concurrently with the thread calling the onNexts. It takes time for a subscribeOn to take effect thus the main thread simply runs ahead and overwrites the subject's current value to the latest in the meantime.
There is no practical reason to use subscribeOn on a Subject in general.

How to perform sequential operation with too much Completable methods

I am trying to save the data on the server to the local database with Room. Since these tables are related to each other, I want the insertion to be done in order.I listen to these operations with RxJava. For example i have school's and season's tables and and that's how I add the data:
fun insertAllSchools(vararg schools: School):Completable=dao.insertAll(*schools)
fun insertAllSeasons(vararg seasons: Season):Completable=dao.insertAll(*seasons)
When I create a separate method for each table, the insertion process is done, but I have to write a disposable method for each of them. Like this:
fun insertAllSchools(allData:ResponseAll){
if(allData.schoolList!=null){
disposable.add(
repositorySchool.insertAll(*allData.schoolList.toTypedArray())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableCompletableObserver(){
override fun onComplete() {
Log.d(TAG,"OnComplete")
}
override fun onError(e: Throwable) {
Log.e(TAG,"Error"+e.localizedMessage)
}
})
)
}
}
When one is complete, I call the other method, but this time there is a lot of unnecessary code.
I have tried different methods to combine these completable methods and work sequentially, but it does not add to the database even though it appears in the logs.
For example, I tried to combine it this way:
if(allData.schoolList!=null){
mObservable = Observable.fromArray(
repositorySchool.clearAllData(),
repositorySchool.insertAll(*allData.schoolList.toTypedArray())
)
disposable.add(
mObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<Completable>() {
override fun onComplete() {
Log.d(TAG,"onComplete")
isDataLoad.value = true
}
override fun onNext(t: Completable) {
Log.d(TAG,"onNext"+t)
}
override fun onError(e: Throwable) {
Log.e(TAG,"onError")
}
})
)
}
I do not receive any errors. How can I combine these completable methods and make them work sequentially. Thanks!
Edit(Solution): It works like this:------------>
if(allData.schoolList!=null) {
disposable.add(
repositorySchool.clearAllData()
.andThen(Completable.defer { repositorySchool.insertAll(*allData.schoolList.toTypedArray()) })
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableCompletableObserver() {
override fun onComplete() {
isDataLoad.value = true
}
override fun onError(e: Throwable) {
Log.e(TAG,""+e.localizedMessage)
}
})
)
}
I disagree with using doOnComplete(). In that case your not combining the Completables into a single Completable event that you can observe. What you probably want is something like doThingA().andThen(Completable.defer(() -> doThingB()) as mentioned in this answer on a similar question.
There is a method called doOnComplete() which you can use to make your second call through a lambda or jack.

RxAndroid / RxLifeCycle - Handling dispose onError instead of onComplete

I'm currently trying to implement RxLifeCycle into my networking with RxJava. I've been using a subclass of Consumer, but for RxLifeCycle, you need to handle onError. So I have moved over to Observer.
The problem with this is that when the call is disposed, it's calling onComplete instead of onError, which I would prefer.
buildle.gradle:
// RxJava
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.3'
compile 'com.trello.rxlifecycle2:rxlifecycle-kotlin:2.2.1'
compile 'com.trello.rxlifecycle2:rxlifecycle-android-lifecycle-kotlin:2.2.1'
My previous NetworkConsumer was structured like this, and I would handle all the results in accept.
NetworkConsumer:
abstract class NetworkConsumer<T> : Consumer<NetworkResponse<T>> {
#Throws(Exception::class)
override fun accept(response: NetworkResponse<T>) {
...
}
// to override
open fun onSuccess(response: T) {}
open fun onComplete() {}
}
My network calls are all structured the same way using Single.
fun getFavorites(): Single<NetworkResponse<Array<MyObject>>>
And I'm using it like this.
service.getFavorites(...)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : NetworkConsumer<Array<MyObject>>() {
override fun onSuccess(response: Array<MyObject>) {
// use response
}
override fun onComplete() {
// do whatever, like hiding the loading view.
loading_view.visibility = View.GONE
}
})
I really like this setup as it allows me to move a lot of the logic from the calling Activity into the NetworkConsumer and only worry about handling the result.
However, with RxLifeCycle, you need to use an Observable instead of a Single. So I created a NetworkObserver to handle this change.
NetworkObserver:
abstract class NetworkObserver<T> : Observer<NetworkResponse<T>> {
override fun onSubscribe(d: Disposable) {}
override fun onNext(response: NetworkResponse<T>) {}
override fun onError(e: Throwable) {}
override fun onComplete() {}
// other functions from NetworkConsumer
}
However, the problem is that onComplete is being called when the network call is disposed, which I would prefer to handle any UI changes in onComplete instead.
For example, I'm showing a loading screen when the network call is started, and I want to hide that loading screen when it's done, regardless if it failed or didn't.
I believe I just need to use a different Class instead of Observer for this, but I'm unsure which Class would work best for this.
The correct answer is SingleObserver, this is perfect for networking.
abstract class NetworkObserver<T> : SingleObserver<NetworkResponse<T>> {
override fun onSubscribe(d: Disposable) {
...
}
override fun onSuccess(response: NetworkResponse<T>) {
... handle onSuccess
}
override fun onError(e: Throwable) {
... cancelled or an error
}
}

RXjava2 method in fromCallable not getting exceuted

I am new to using rxjava and I am trying to run a function in background using rxjava2 but the method is not called the code I am using is given below let me know if its the right way to execute a function in background:
Observable.fromCallable<OrderItem>(Callable {
saveToDb(existingQty, newOty, product_id)
}).doOnSubscribe {
object : Observable<OrderItem>() {
override fun subscribeActual(emitter: Observer<in OrderItem>?) {
try {
val orderItem = saveToDb(existingQty, newOty, product_id)
emitter?.onNext(orderItem)
emitter?.onComplete()
} catch (e: Exception) {
emitter?.onError(e)
}
}
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).doOnSubscribe {
object : Observer<OrderItem> {
override fun onComplete() {
}
override fun onNext(t: OrderItem) {
}
override fun onError(e: Throwable) {
}
override fun onSubscribe(d: Disposable) {
}
}
}
You are dong it wrong way. doOnSubscribe() operator is called when observable is subscribed using subscribe() method and you haven't subscribed the observable using subscribe() method.
You have called saveToDb method in callable, then why are you calling it in doOnSubscribe? it doesn't make sense.
You should have written following code:
Observable.fromCallable { saveToDb(existingQty, newOty, product_id) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ orderItem ->
// set values to UI
}, { e ->
// handle exception if any
}, {
// on complete
})
to work with your logic.
DoOnSubscribe means "do when someone subscribe to it". But there is no subscribe in your code. Maybe you want to use subsribe instead of doOnSubscribe

LiveData observer does not trigger on a callback

LiveData observer does not trigger when a callback is emitted. But if I put the observable data in a function and change the data it works just fine. Please any ideas what would it be?
fun connect(address: String){
protocolARC.value = ProtocolARC() //OKAY!!!!
bleManager.gattClient.onCreate(getApplication(), address, object : GattClient.OnCounterReadListener {
override fun onCounterRead(value: Int) {
Log.d("HURRAY", "read")
protocolARC.value = ProtocolARC() //NOT OKAY?????
}
override fun onConnected(success: Boolean) {
stopScan()
}
})
}
The problem was in a callback. It was not being triggered from the main thread.

Categories

Resources