Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep subscriber after onError(RxJava)

1st, I tried

// used retrofit
public interface ApiService {
    @GET(/get_some_data)
    Observable<SomeData> getSomeData();
}



// clickStream created by onClick event
// No.1
clickStream
    .flatMap(e -> apiService.getSomeData())
    .subscribe(
        success -> Log.d("tag", "success"),
        error -> Log.d("tag", "error"),
        () -> Log.d("tag", "complete"))

this is fine if getSomeData() is success. I can get some data each click.

but if occur error, unsubscribed. (so click is not works after error)


2nd, I tried below.(with onErrorResumeNext) but unsubscribed.

(didn't call onError, but called onComplete. so unsubscribed)

// No.2
clickStream
    .flatMap(e -> apiService.getSomeData())
    .onErrorResumeNext(throwable -> Observable.empty())  // add this line
    .subscribe(
        success -> Log.d("tag", "success"),
        error -> Log.d("tag", "error"),
        () -> Log.d("tag", "complete"))

3rd, I tried below.(with retry)

// No.3
clickStream
    .flatMap(e -> apiService.getSomeData())
    .retry(5)                                            // add this line
    .subscribe(
        success -> Log.d("tag", "success"),
        error -> Log.d("tag", "error"),
        () -> Log.d("tag", "complete"))

this is better than No.1. but unscribed.


I want to make refresh button that works after error.

I want to know

  1. Can I keep or re-subscribe subscriber?
  2. Is this a proper way in Rxjava?

sorry for my poor English.

like image 856
kyanro Avatar asked Jan 14 '15 07:01

kyanro


1 Answers

Your Nr. 2 was quite close - try this:

clickStream
.flatMap(e -> apiService.getSomeData()
    .onErrorResumeNext(throwable -> Observable.empty()))  // add this line
.subscribe(
    success -> Log.d("tag", "success"),
    error -> Log.d("tag", "error"),
    () -> Log.d("tag", "complete"))

Notice that I just moved one closing parenthesis so that the onErrorResumeNext is now called after every error and is part of the "inner" Observable.

like image 112
david.mihola Avatar answered Oct 26 '22 12:10

david.mihola