I am new in rxjava, so please don't be strict...
I have request lice next one:
Observable<Login>login(String l, String p){
return api.loginUser(l,p)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<Response<Login>, Observable<? extends Login>>() {
@Override
public Observable<? extends Login> call(Response<Login> r) {
switch (r.code()){
case 200:
requestOk(r);
break;
case 202:
//need to Repeat
login.timeout(2000,TimeUnit.Milliseconds);
break;
default:
//
}
}
});
}
Observable<Login> requestOk(final Response<Login> r){
return Observable.create(new Observable.OnSubscribe<Login>(){
@Override
public void call(Subscriber<? super Login> subscriber) {
if (subscriber.isUnsubscribed()) return;
subscriber.onNext(r.body());
subscriber.onCompleted();
}
});
}
It works ok. But there will be a lot of other requests where I need to check request code in case of repeat.
So I was trying to create custom Func1 - universal for all request:
private <T>Func1<? super Response<T>, ? extends Observable<? extends T>> customFunc(final Observable<T> o) {
return new Func1<Response<T>, Observable<? extends T>>() {
@Override
public Observable<? extends T> call(Response<T> r) {
switch (r.code()){
case 200:
//
break;
case 202:
//need to Repeat
return o.timeout(2000,TimeUnit.Milliseconds);
break;
default:
//
}
};
};
}
I am stuck with putting current observable from login observable into customFunc.
I believe there must be some other, easier and correct way how to do this. Will be glad any help!
You can use
Transformer
in order to create a generic status code verifier:this transformer will take any
Observable
ofResponse<T>
and will transform it toObservable
ofT
, that emits errors according to your strategy.Then use it with
compose()
operator:Now you have an
Observable
that will emitonError
with your desired exception according to your status code handling.Now, you can retry on error like with any
Observable
withretry
operator, for instance like this:BTW, some comments:
requestOk - you definitely don't need to create
Observable
for emitting specific value once, just use thejust()
operator, like in theStatusCodeVerifierTransformer
example. (or for any other synchronize operation, you have plenty of operators likefromCallable()
,just()
,from()
)Generally,
create()
is not a safe method of creating anObservable
anymore.