gpt4 book ai didi

java - 如何在 Flowable 上执行操作

转载 作者:行者123 更新时间:2023-12-02 05:10:09 30 4
gpt4 key购买 nike

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

另外,我如何对来自 Flowable f1 的所有项目执行操作,但在 n 个项目之后创建新的 Flowable f2来自f1 .

最佳答案

对于您的第一个问题,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的RxJava javadoc ( http://reactivex.io/RxJava/2.x/javadoc/index.html?io/reactivex/Flowable.html )。它有很多运算符,弹珠图很好地解释了每个运算符的作用。

关于java - 如何在 Flowable 上执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56330797/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com