您可以使用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;
}
}