Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh observable in RxJava?

I have an observable, which wraps a HTTP request

mObservable =  retryObservable(mService.getAddressList(getUserId(), true, 1, Integer.MAX_VALUE, "id", true)
            .map(r -> {
                return r.getItems();
            })
            .observeOn(AndroidSchedulers.mainThread()));

then subscription

mSubscription = mObservable.subscribe(items -> {
                mAddressAdapter.swapItems(items);
            }, getActivityBase()::showError);

When the subscription initialization comes, cold observable is activated and HTTP request fires. Now, I know that underlying data has changed, and I need to make same, but new request. I've tried

mSubscription.unsubscribe();

then calling

mObservable.subscribe(items -> {doSomething();})

again, as from my understanding, subscribing should trigger the observable, but it doesnt work. Any suggestions ?

like image 380
PetoU Avatar asked Dec 01 '14 21:12

PetoU


1 Answers

Once the Observable is completed it doesn't publish any new items. It's Rx contract.

Wrap your code into a method and create a new observable each time.

Observable<?> getObservable() {
    return retryObservable(mService.getAddressList(getUserId(), true, 1, Integer.MAX_VALUE, "id", true)
            .map(r -> {
                return r.getItems();
            })
            .observeOn(AndroidSchedulers.mainThread()));
}


As @DaveSexton mentioned in the comment there's even better approach using defer function in RxJava

Do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription

Pass defer( ) an Observable factory function (a function that generates Observables), and defer( ) will return an Observable that will call this function to generate its Observable sequence afresh each time a new Subscriber subscribes.

More here: https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#defer

like image 60
tomrozb Avatar answered Sep 30 '22 18:09

tomrozb