Android 如何关闭CachedObservable
我有无尽的溪流(这根本不是所谓的“完成”)。我在其中缓存最后一个值:Android 如何关闭CachedObservable,android,rx-java,Android,Rx Java,我有无尽的溪流(这根本不是所谓的“完成”)。我在其中缓存最后一个值: Observable<T> endlessStream = createStream().cache(); Subscription s1 = endlessStream.subscribe(...) Subscription s2 = endlessStream.subscribe(...) 但是CachedObservable将始终存储到源流的连接(从createStream()返回)。这会导致内存泄漏。
Observable<T> endlessStream = createStream().cache();
Subscription s1 = endlessStream.subscribe(...)
Subscription s2 = endlessStream.subscribe(...)
但是CachedObservable将始终存储到源流的连接(从createStream()
返回)。这会导致内存泄漏。
如何断开CachedObservable
与源可观测数据的连接
更多信息:
CachedObservable
包含字段state
,其中包含对源观测值的序列化订阅(连接
)。
如果我叫下一个黑客,一切都会好起来:
private void disconnectCachedObservable(CachedObservable<T> observable) {
try {
Field fieldState = CachedObservable.class.getDeclaredField("state");
fieldState.setAccessible(true);
Object state = fieldState.get(observable);
Field fieldConnection = state.getClass().getDeclaredField("connection");
fieldConnection.setAccessible(true);
SerialSubscription subscription = (SerialSubscription) fieldConnection.get(state);
subscription.unsubscribe();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private void disconnectCachedObservable(可观察到CachedObservable){
试一试{
fieldState=CachedObservable.class.getDeclaredField(“状态”);
fieldState.setAccessible(true);
对象状态=fieldState.get(可观察);
fieldConnection=state.getClass().getDeclaredField(“连接”);
fieldConnection.setAccessible(true);
SerialSubscription=(SerialSubscription)fieldConnection.get(状态);
订阅。取消订阅();
}捕获(无此字段例外){
e、 printStackTrace();
}捕获(非法访问例外e){
e、 printStackTrace();
}
}
但反射不是好的解决方案:(找到了解决方案:
操作员缓存具有与操作员重播+自动连接(1)类似的行为
这样你就可以通过订阅来阻止上游
private void disconnectCachedObservable(CachedObservable<T> observable) {
try {
Field fieldState = CachedObservable.class.getDeclaredField("state");
fieldState.setAccessible(true);
Object state = fieldState.get(observable);
Field fieldConnection = state.getClass().getDeclaredField("connection");
fieldConnection.setAccessible(true);
SerialSubscription subscription = (SerialSubscription) fieldConnection.get(state);
subscription.unsubscribe();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
replay().autoConnect(1, toStop -> { /* store Subscription to cancel later */ });