前言
前面写过RxJava类似观察者模式,但是一直没提到RxJava如何取消订阅,今天就来学习一下.
Subscription
RxJava中有个叫做Subscription
的接口,可以用来取消订阅.
public interface Subscription {
/**
* Stops the receipt of notifications on the {@link Subscriber} that was registered when this Subscription
* was received.
* <p>
* This allows unregistering an {@link Subscriber} before it has finished receiving all events (i.e. before
* onCompleted is called).
*/
void unsubscribe();
/**
* Indicates whether this {@code Subscription} is currently unsubscribed.
*
* @return {@code true} if this {@code Subscription} is currently unsubscribed, {@code false} otherwise
*/
boolean isUnsubscribed();
}
从上面可以看到,我们只需要调用unsubscribe
就可以取消订阅,那么如何得到一个Subscription
对象呢?
其实很简单:Observable.subscribe()
方法可以返回一个Subscription
的