如何在订阅observable时确保GC

时间:2018-05-01 21:11:35

标签: rx-java rx-java2

我有一个接受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;
}

1 个答案:

答案 0 :(得分:0)

您将不得不依赖用户以某种方式取消订阅。为什么不将它们传回disposable并让他们使用它?

static class Helper {
    Disposable subscribeTo(Observable<Object> observable) {
        return observable.subscribe(someObject -> {
            // do something with someObject;
        });
    }
}