在 RxJava 2 的 onComplete() 之前执行代码?
Execute code just before onComplete() in RxJava 2?
我需要在 RxLifecycle
处理之前关闭我的 observable 中的套接字连接。我怎样才能做到这一点?
您可以尝试使用 doFinally
Calls the specified action after this Observable signals onError or onCompleted or gets disposed by the downstream.
如果你想做一个动作,就在订阅者取消订阅之前,你可以使用运算符 doOnUnsubscribe
@Test
public void testDoOnUnsubscribe() {
Integer[] numbers = {0, 1, 2, 3, 4};
Observable.from(numbers)
.doOnUnsubscribe(() -> System.out.println("Last action must be done here"))
.subscribe(number -> System.out.println("number:" + number),
System.out::println,
() -> System.out.println("End of pipeline"));
}
应该按这个顺序打印
number:0
number:1
number:2
number:3
number:4
End of pipeline
Last action must be done here
如果您使用过滤器和映射来迭代对象以组合结果,也可以尝试此操作。
.doOnTerminate(() -> Log.d(LOGGER, "terminated"))
我需要在 RxLifecycle
处理之前关闭我的 observable 中的套接字连接。我怎样才能做到这一点?
您可以尝试使用 doFinally
Calls the specified action after this Observable signals onError or onCompleted or gets disposed by the downstream.
如果你想做一个动作,就在订阅者取消订阅之前,你可以使用运算符 doOnUnsubscribe
@Test
public void testDoOnUnsubscribe() {
Integer[] numbers = {0, 1, 2, 3, 4};
Observable.from(numbers)
.doOnUnsubscribe(() -> System.out.println("Last action must be done here"))
.subscribe(number -> System.out.println("number:" + number),
System.out::println,
() -> System.out.println("End of pipeline"));
}
应该按这个顺序打印
number:0
number:1
number:2
number:3
number:4
End of pipeline
Last action must be done here
如果您使用过滤器和映射来迭代对象以组合结果,也可以尝试此操作。
.doOnTerminate(() -> Log.d(LOGGER, "terminated"))