匿名类包含对封闭类的引用。
在以下示例中,我创建了一个小型Activity。在onCreate方法中,我只是在另一个Thread上添加一个计时器,添加一个CompositeDisposable并在onDestroy中清除它。
显然没有CompositeDisposable,它会造成内存泄漏。使用CompositeDisposable,它不会产生任何内存泄漏,但它是如何工作的?
RxJava只是中断线程并在每次回调时放置null?你可以提供一些在RxJava源代码中执行此工作的行,我想它在dispose方法附近。
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private CompositeDisposable composite = new CompositeDisposable();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
composite.add(Flowable
.just(1)
.timer(90, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.subscribeWith(new DisposableSubscriber<Long>() {
@Override
public void onNext(Long aLong) { sayHello(); }
@Override
public void onError(Throwable t) { sayHello(); }
@Override
public void onComplete() { sayHello(); }
}));
}
@Override
protected void onDestroy() {
super.onDestroy();
composite.clear();
}
public void sayHello () { Log.w(TAG, "Hello everyone"); }
答案 0 :(得分:4)
正是dispose
方法的来源。您也可以在IDE中的IntelliJ中 Ctrl + B 或者⌘B跳转到库中方法的来源在Mac上,在Eclipse中它是 F3 。
无论如何,这里是dispose
方法的来源(评论我的):
@Override
public void dispose() {
if (disposed) { // nothing to do
return;
}
OpenHashSet<Disposable> set; // this is the same type as our field that holds the Disposables
synchronized (this) {
if (disposed) {
return; // another thread did it while we got our lock, so nothing to do
}
disposed = true; // setting this flag is safe now, we're the only ones disposing
set = resources; // the references are now in this local variable
resources = null; // our field no longer has the references
}
dispose(set); // from here on out, only this method has the references to the Disposables
}
然后是我们在最后一行上面调用的dispose(OpenHashSet<Disposable>)
方法的完整代码(主要是错误处理,我相信这是自我解释的):
/**
* Dispose the contents of the OpenHashSet by suppressing non-fatal
* Throwables till the end.
* @param set the OpenHashSet to dispose elements of
*/
void dispose(OpenHashSet<Disposable> set) {
if (set == null) {
return;
}
List<Throwable> errors = null;
Object[] array = set.keys();
for (Object o : array) {
if (o instanceof Disposable) {
try {
((Disposable) o).dispose();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
if (errors == null) {
errors = new ArrayList<Throwable>();
}
errors.add(ex);
}
}
}
if (errors != null) {
if (errors.size() == 1) {
throw ExceptionHelper.wrapOrThrow(errors.get(0));
}
throw new CompositeException(errors);
}
}
正如您所看到的,在该方法结束时,set
现在可以被垃圾收集,因为没有人持有对它的引用。