我有一个接受Observable
并订阅它的课程。
static class Helper {
void subscribeTo(Observable<Object> observable) {
observable.subscribe(someObject -> {
// do something with someObject;
});
}
}
当设置为null
时,此类本身是否可以确定取消订阅?
void main() {
Helper helper = new Helper();
Observable<Object> observable = ... // an observable that never completes
helper.subscribeTo(observable);
...
helper = null; // helper will never be GC'd because observable never completes
}
在此示例中,Helper
很容易被滥用,如果你给它一个永无止境的Observable
。
我能想出的最佳解决方案是允许(但不强制执行)实例化类在设置为null之前清除辅助类:
static class Helper {
private Disposable disposable;
void subscribeTo(Observable<Object> observable) {
// do something with someObject;
disposable = observable.subscribe(someObject -> {
// do something with someObject;
});
}
void cleanup() {
disposable.dispose();
}
}
void main() {
Helper helper = new Helper();
Observable<Object> observable = ... // an observable that never completes
helper.subscribeTo(observable);
...
helper.cleanup();
helper = null;
}
答案 0 :(得分:0)
您将不得不依赖用户以某种方式取消订阅。为什么不将它们传回disposable
并让他们使用它?
static class Helper {
Disposable subscribeTo(Observable<Object> observable) {
return observable.subscribe(someObject -> {
// do something with someObject;
});
}
}