问题描述
我正在使用RxJava,我有一个 Observable
,里面有多个项目。我想要做的是在第一项上运行函数A,在所有这些项上运行函数B,在 Observable
完成时运行函数C:
I am using RxJava and I have an Observable
with multiple items inside. What I would like to do is run function A on the first item, function B on all of them and function C when the Observable
is completed:
-----1-----2-----3-----|-->
| | | |
run A | | |
| | | |
run B run B run B |
|
run C
有一种聪明的方式用lambda函数表达这个吗?我已经有了以下解决方案,但它看起来很难看,我怀疑有更好的方法可以做到这一点:
is there a clever way of expressing this with lambda functions? I have the following solution already, but it looks ugly and I suspect that there is a better way to do this:
observable.subscribe(
new Action1<Item>() {
boolean first = true;
@Override
public void call(Item item) {
if (first) {
runA(item);
first = false;
}
runB(fax1);
}
},
throwable -> {},
() -> runC());
推荐答案
我想我找到了一个简单的解决方案我自己:
I guess I've found an easy solution for this myself:
Observable<Integer> observable = Observable.just(1, 2, 3).share();
observable.take(1).subscribe(this::runA);
observable.subscribe(
this::runB,
throwable -> {},
this::runC);
这是单线程的,它似乎也可以工作多线程,但我不得不承认我到目前为止,我对此并不太自信。
This works single-threaded and it seems to work multi-threaded too, but I have to admit I'm not too confident about that so far.
这篇关于RxJava:如何表达doOnFirst()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!