Issue
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.
Solution
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
}
}
Answered By - advice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.