RxAndroid / RxLifeCycle - Handling dispose onError instead of onComplete - android

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
}
}

Related

How can I ensure that a Retrofit function is working only once

I have an app with different API operations made with retrofit. Unfortunately, the API I am using doesn't have an update function so instead of updating, I am currently deleting, and adding with updated values.
This solution works OK when my update clicks are more than half a second apart, but when I click faster It causes duplications.
I am using Data Binding and MVVM. So, function call route is as following:
XML -> Fragment (Adapter in this case) -> ViewModel -> Repository
fun updateCartItem(cart: Cart) {
apiService.deleteCartItem(cart.cartFoodId,cart.orderUsername).enqueue(object: Callback<CartResponse> {
override fun onResponse(call: Call<CartResponse>?, response: Response<CartResponse>?) {
apiService.addFoodToCart(
cart.foodName,
cart.foodPicture,
cart.foodPrice,
cart.foodQuantity,
cart.orderUsername
).enqueue(object: Callback<CartResponse> {
override fun onResponse(call: Call<CartResponse>?, response: Response<CartResponse>?) {
fetchCart(cart.orderUsername)
}
override fun onFailure(call: Call<CartResponse>?, t: Throwable?) {}
})
}
override fun onFailure(call: Call<CartResponse>?, t: Throwable?) {}
})
}
I tried to add #Synchronized annotation to my function, but it didn't help.
Basically what I need is a way to ensure my update function is working only once.

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 make 2 series of request using LiveData and ViewModel in Android?

I am learning MVVM and Android architecture component.
I need to make 2 requests to server from my fragment/activity, the result from first request will be used as input parameter for second request, after those request are good, then navigate to next fragment/activity
in old way, the code in my fragment/activity will be like this
class FragmentA : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getUserData("example#email.com")
}
fun getUserData(email: String) {
// making request using retrofit
call.enqueue(object: Callback<RestaurantListBaseResponse> {
override fun onFailure(call: Call<RestaurantListBaseResponse>, t: Throwable) {
}
override fun onResponse(call: Call<User>, response: Response<User>) {
val user = response.body()!!.user
if (user.isVerified) {
createPost(user.id)
}
}
})
}
fun createPost(userID: String) {
// making request using retrofit
call.enqueue(object: Callback<RestaurantListBaseResponse> {
override fun onFailure(call: Call<RestaurantListBaseResponse>, t: Throwable) {
}
override fun onResponse(call: Call<PostResponse>, response: Response<PostResponse>) {
val isSuccessfull = response.body()!!.isSuccessfull
if (isSuccessfull) {
// Navigate to next fragment or activity
}
}
})
}
}
but now I am confused how to convert this using livedata and viewmodel. the tutorials I watch are too simple and I am confused if I have to handle 2 request in series like this using livedata and viewmodel, I don't know the common practise to solve this
please don't use kotlin coroutine, I am a beginner :(
Java or Kotlin are okay, I can read Java as well

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.

RxJava not running on Background thread

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.

Categories

Resources