什么时候在 ViewModel 中处理 RxJava2 Disposable?
When to dispose RxJava2 Disposable in ViewModel?
我正在使用 ViewModel from Android Architecture Components in my app. In the ViewModel, I'm using RxJava2 订阅,订阅后我会保留 Disposable
对象。以前,当我在 Activity
中这样做时,我习惯于在 onDestroy()
中处理 Disposable
- 以避免内存泄漏:
@Override
protected void onDestroy() {
disposable.dispose();
super.onDestroy();
}
我应该何时以及如何在 ViewModel
中处理它?我真的需要这样做吗?
使用 onCleared 方法
@Override
protected void onCleared () {
disposable.dispose();
super.onCleared ();
}
您可以使用 LiveDataReactiveStreams#fromPublisher(Publisher<T>)
并从视图模型公开结果 LiveData
,而不是在视图模型中订阅和处置。
例如:
public class ExampleViewModel {
private static final long TIME_FOR_ANSWER = 1000;
private static final long DELAY = 25;
private final LiveData<Long> remainingTime;
ExampleViewModel() {
long start = 0;
long count = TIME_FOR_ANSWER / DELAY + 1;
Flowable<Long> flowable =
Flowable.intervalRange(start, count, 0, DELAY, TimeUnit.MILLISECONDS)
.map(i -> TIME_FOR_ANSWER - DELAY * i);
remainingTime = LiveDataReactiveStreams.fromPublisher(flowable);
}
public LiveData<Long> getRemainingTime() {
return remainingTime;
}
}
我正在使用 ViewModel from Android Architecture Components in my app. In the ViewModel, I'm using RxJava2 订阅,订阅后我会保留 Disposable
对象。以前,当我在 Activity
中这样做时,我习惯于在 onDestroy()
中处理 Disposable
- 以避免内存泄漏:
@Override
protected void onDestroy() {
disposable.dispose();
super.onDestroy();
}
我应该何时以及如何在 ViewModel
中处理它?我真的需要这样做吗?
使用 onCleared 方法
@Override
protected void onCleared () {
disposable.dispose();
super.onCleared ();
}
您可以使用 LiveDataReactiveStreams#fromPublisher(Publisher<T>)
并从视图模型公开结果 LiveData
,而不是在视图模型中订阅和处置。
例如:
public class ExampleViewModel {
private static final long TIME_FOR_ANSWER = 1000;
private static final long DELAY = 25;
private final LiveData<Long> remainingTime;
ExampleViewModel() {
long start = 0;
long count = TIME_FOR_ANSWER / DELAY + 1;
Flowable<Long> flowable =
Flowable.intervalRange(start, count, 0, DELAY, TimeUnit.MILLISECONDS)
.map(i -> TIME_FOR_ANSWER - DELAY * i);
remainingTime = LiveDataReactiveStreams.fromPublisher(flowable);
}
public LiveData<Long> getRemainingTime() {
return remainingTime;
}
}