dispose方法:
CompositeDisposable是多个Disposable的集合,这里测试CompositeDisposable在执行dispose方法后,对后续添加进来的事件是否有影响:
public class MainActivity extends AppCompatActivity {
private CompositeDisposable disposable = new CompositeDisposable();
protected void onCreate(Bundle savedInstanceState) {
disposable.add(Observable.just(0).delay(1, TimeUnit.SECONDS).subscribe(n -> {
Log.e(TAG, "receive event 0");
}));
disposable.dispose();
Log.e(TAG, "isDisposed" + disposable.isDisposed()); //true
disposable.add(Observable.just(1).delay(100, TimeUnit.MICROSECONDS).subscribe(n -> {
Log.e(TAG, "receive event 1");
}));
}
测试发现,事件1无法正常被接收,即一旦CompositeDisposable执行了dispose方法,它就会进入isDisposed状态,后续添加进来新的disposable都会直接被dispose掉。但是如果时间1的延时足够小,还是可以收到事件1的,所以推测dispose方法是个异步方法;
clear方法:
如果想使CompositeDisposable只取消已经add的Disposable,而后续新添加的Disposable不受影响,可以使用clear方法
clear方法不只是简单地将原来添加的事件删除,而且还会dispose掉这些已添加的事件;
public class MainActivity extends AppCompatActivity {
private CompositeDisposable disposable = new CompositeDisposable();
protected void onCreate(Bundle savedInstanceState) {
disposable.add(Observable.just(0).delay(1, TimeUnit.SECONDS).subscribe(n -> {
Log.e(TAG, "receive event 0");
}));
disposable.clear();
Log.e(TAG, "isDisposed" + disposable.isDisposed()); //false
disposable.add(Observable.just(1).delay(100, TimeUnit.MICROSECONDS).subscribe(n -> {
Log.e(TAG, "receive event 1");
}));
}
测试可知clear方法不会影响后续Disposable正常接收事件;
CompositeDisposable源码:
public final class CompositeDisposable implements Disposable, DisposableContainer {
OpenHashSet<Disposable> resources;
volatile boolean disposed;
@Override
public void dispose() { //注意dispose和clear方法的对比
if (disposed) {
return;
}
OpenHashSet<Disposable> set;
synchronized (this) {
if (disposed) {
return;
}
disposed = true; //clear方法只是缺少了这句
set = resources;
resources = null;
}
dispose(set); //这个方法会遍历set逐个dispose
}
public void clear() { //clear方法和dispose方法非常相似,唯一的区别就在于,clear没有把disposed置为true
if (disposed) {
return;
}
OpenHashSet<Disposable> set;
synchronized (this) {
if (disposed) {
return;
}
set = resources;
resources = null;
}
dispose(set); //clear也会遍历set逐个dispose
}
@Override
public boolean add(@NonNull Disposable d) {
ObjectHelper.requireNonNull(d, "d is null");
if (!disposed) { //如果没有不在disposed状态,就把d添加到set中,返回ture;
synchronized (this) {
if (!disposed) {
OpenHashSet<Disposable> set = resources;
if (set == null) {
set = new OpenHashSet<Disposable>();
resources = set;
}
set.add(d);
return true;
}
}
}
d.dispose(); //如果已经在dispose状态了,直接dispose掉这个消息,并返回false;
return false;
}
}