When to unsubscribe a subscription

前端 未结 3 1975
清酒与你
清酒与你 2021-02-03 20:54

I have a question regarding how to unsubscribe an observable. I have two codes and I\'m not really sure about which one is better.

Example 1 -> Unsubscribe the subscribe

3条回答
  •  既然无缘
    2021-02-03 21:20

    I think that depends on your needs. If the activity won't wait for any other calls, I suppose you could unsubscribe inside onCompleted().

    I always unsubscribe in onDestroy()

    @Override
    protected void onDestroy() {
        super.onDestroy();
    
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }
    

    EDIT: take a look at http://reactivex.io/RxJava/javadoc/rx/subscriptions/CompositeSubscription.html

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();
    
    private void doSomething() {
        mCompositeSubscription.add(
            AndroidObservable.bindActivity(this, Observable.just("Hello, World!"))
           .subscribe(s -> System.out.println(s)));
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeSubscription.unsubscribe();
    }
    

提交回复
热议问题