我有两个观测值,我想从每个观测值中取走,直到两个观测值都没有剩下。有运营商可以这样做吗?让我向您展示一个例子,说明我已经尝试过并且想要完成的事情:
Observable<String> observable = Observable.just("hello","are", "doing");
Observable<String> observable2 = Observable.just("how","you","today");
我想“减少”这一点,以便最终的排放量是“ 你好,你今天好吗
在这里我尝试使用扫描,但是它的工作方式更像是累积,并且得到以下结果:
Observable.merge(observable, observable2).reduce(new BiFunction<String, String, String>() {
@Override
public String apply(String wordAccum1, String word2) {
return wordAccum1 + " " + word2;
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String sentence) throws Exception {
Log.v("consumerResult",sentence+"");
}
});
日志输出显示: ConsumerResult:您好,您今天过得如何
我该如何连续取每个?
答案 0 :(得分:5)
尝试一下
Observable<String> observable = Observable.just("hello", "are", "doing");
Observable<String> observable2 = Observable.just("how", "you", "today");
observable.zipWith(observable2, new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) throws Exception {
return s+" "+s2;
}
}).reduce(new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) throws Exception {
return s+ " " + s2;
}
}).subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
System.out.println(s); // this will emit with "hello how are you doing today"
}
});
如果您使用的是Java 8,则可以使用lambda减少相同的代码,如下所示
observable.zipWith(observable2, (s, s2) -> s + " " + s2)
.reduce((s, s2) -> s +" "+ s2).subscribe(System.out::println);