让我们说当s1和o1完成时我需要做,但是s1只发生一次而o1多次发生,每次o1发生时我都需要做一些事情。我怎么能这样做?
我尝试过以下代码,
val s1 = Single.fromCallable {
Log.d("so","executing s1");
"hello";
}.cache();
var emitter:ObservableEmitter<String>? = null;
val o1 = Observable.create<String> {
emitter = it;
}
Observable.zip(s1.toObservable(),o1,
BiFunction<String, String, Array<String>>() { t1, t2 -> arrayOf(t1,t2); })
.subscribe { t1 ->
Log.d("so", "Result = " + t1.joinToString(","));
}
emitter?.onNext("homer");
emitter?.onNext("marge");
emitter?.onNext("bart");
Log.d("so", "Done");
但结果是
executing s1,
Result = hello,homer
Done
当我预期的结果是
时executing s1,
Result = hello,homer
Result = hello,marge
Result = hello,bart
Done
答案 0 :(得分:0)
使用flatMap
:
s1.flatMapObservable({ t1 -> o2.map({ t2 -> arrayOf(t1, t2) }) })
也可以使用PublishSubject
而不是偷偷溜出发射器:
val o2 = PublishSubject.create();
s1.flatMapObservable({ t1 -> o2.map({ t2 -> arrayOf(t1, t2) }) })
.subscribe { t1 ->
Log.d("so", "Result = " + t1.joinToString(","));
}
o2.onNext("homer");
o2.onNext("marge");
o2.onNext("bart");
Log.d("so", "Done");