如何在 Flowable 上做动作

How to do action on Flowable

你好我是 RxJava 的新手,我有一个接收 Flowable<Item> f2 的 class,我需要从中获取值,而不更改任何数据(将值保存到本地缓存)。然后将其与其他 Flowable f1 连接并发送到更高级别 class。是否可以只从 f2 发出一次值?

另外,我如何对来自 Flowable f1 的所有项目执行操作,但是在 n 个项目从 f1.

创建新的 Flowable f2 之后

对于您的第一个问题,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。它有很多运算符,弹珠图很好地解释了每个运算符的作用。