您好,我是RxJava的新手,我有一个接收Group
的类,我需要从中获取值,而无需更改任何数据(将值保存到本地缓存)。然后将其与其他Flowable<Item> f2
连接起来,并将其发送到更高级别的类。只能从Flowable f1
发出一次值吗?
我也该如何对来自f2
的所有项目执行操作,但是在n个项目之后,要从Flowable f1
创建新的Flowable f2
。
答案 0 :(得分:0)
对于第一个问题,doOnNext()
可能就是您要寻找的(http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Flowable.html#doOnNext-io.reactivex.functions.Consumer-)。
private static void main() {
Flowable<String> f2 = Flowable.just("a", "b", "c", "d", "e");
Flowable<String> f1 = Flowable.just("z", "x", "y");
f2.doOnNext(n -> System.out.println("saving " + n))
.concatWith(f1)
.subscribe(System.out::println);
Flowable.timer(10, SECONDS) // Just to block the main thread for a while
.blockingSubscribe();
}
对于第二个问题,这取决于您是否要删除第n个之后的项目。如果是这样,则可以使用take()
,否则请使用buffer()
。
public static void main(String[] args) {
Flowable<String> f1 = Flowable.just("a", "b", "c", "d", "e");
Flowable<String> f2 = Flowable.just("z", "x", "y");
f1.doOnNext(n -> System.out.println("action on " + n))
.take(3)
.subscribe(System.out::println);
System.out.println("------------------------");
System.out.println("Other possible use case:");
System.out.println("------------------------");
f1.doOnNext(n -> System.out.println("another action on " + n))
.buffer(3)
.flatMap(l -> Flowable.fromIterable(l).map(s -> "Hello " + s))
.subscribe(System.out::println);
Flowable.timer(10, SECONDS) // Just to block the main thread for a while
.blockingSubscribe();
}
您可以查看Flowable
(http://reactivex.io/RxJava/2.x/javadoc/index.html?io/reactivex/Flowable.html)的RxJava Javadoc。它有很多运算符,大理石图很好地说明了每个运算符的作用。