【问题标题】:How to unsubscribe observable or subscription in RxJava2 ? or Do I really need to?如何在 RxJava2 中取消订阅 observable 或订阅?或者我真的需要吗?
【发布时间】:2017-08-11 08:58:08
【问题描述】:

如何在 RxJava2 中取消订阅 observable 或订阅?或者我真的需要吗?

//Initialising Obersvable         
    Observable<SearchSuggestions> observable = NetworkContext.api.getSearch("");
        //subscribing obersvable on another thread and observing on main thread

            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<SearchSuggestions>() {
                        @Override
                        public void accept(SearchSuggestions searchSuggestions) throws Exception {
    // here I receive the fetched results

                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
    //here the error
                        }
                    });

【问题讨论】:

标签: android rx-android rx-java2


【解决方案1】:

要取消订阅,也许你应该声明

private Subscription subscription;

//and use it :
subscription = observable.subscribeOn(..)...;

任何时候你想取消订阅只需调用,但我会建议取消订阅 onDestroy(活动)或 onDestroyView(片段)

if (subscription != null && subscription.isUnsubscribed()) {
        subscription.unsubscribe();
 }

【讨论】:

  • rxJava2 中不存在
猜你喜欢
  • 1970-01-01
  • 2020-05-30
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多