我有一个observable,它包装了一个HTTP请求
mObservable = retryObservable(mService.getAddressList(getUserId(),true,1,Integer.MAX_VALUE,"id",true) .map(r -> { return r.getItems(); }) .observeOn(AndroidSchedulers.mainThread()));
然后订阅
mSubscription = mObservable.subscribe(items -> { mAddressAdapter.swapItems(items); },getActivityBase()::showError);
订阅初始化到来时,将激活cold observable并触发HTTP请求.现在,我知道基础数据已经发生了变化,我需要做出同样的新请求.
我试过了
mSubscription.unsubscribe();
然后打电话
mObservable.subscribe(items -> {doSomething();})
再次,从我的理解,订阅应该触发可观察,但它不起作用.
有什么建议 ?
解决方法
Observable完成后,它不会发布任何新项目.这是Rx合同.
将代码包装到方法中,每次都创建一个新的observable.
Observable<?> getObservable() { return retryObservable(mService.getAddressList(getUserId(),true) .map(r -> { return r.getItems(); }) .observeOn(AndroidSchedulers.mainThread())); }
正如@DaveSexton在评论中提到的那样,在RxJava中使用延迟函数甚至更好
Do not create the Observable until a Subscriber subscribes; create a
fresh Observable on each subscriptionPass 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.
更多这里:https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#defer