0

假设我有一个BehaviorProcessor包含一些值的v

现在,如果我想异步请求一些数据,这取决于v我会这样做:

val res = v.flatMapSingle { asyncRequest(it) }

现在让我们记录这个块的所有调用(映射器)

val res = v.flatMapSingle {
    println("mapper")
    asyncRequest(it)
}

它将打印mapper多次,这意味着asyncRequest被多次调用,似乎每次其他依赖流都被subscribe调用

我试图避免多次映射器调用(从而避免多次asyncRequest调用)。

有没有办法用标准的 rxjava2 utils 做到这一点?

4

1 回答 1

1

使用cache()运算符。它将缓存flatMapSingle.

BehaviorProcessor<String> v = BehaviorProcessor.create();
Flowable<String> res = v.flatMapSingle(item -> {
    System.out.println("mapper");
    return asyncRequest(item);
    })
        .cache();
v.onNext("test");
res.subscribe(s->System.out.println("subscribe1 received: "+ s));
res.subscribe(s->System.out.println("subscribe2 received: "+ s));
v.onNext("test2");

生产

mapper
mapper
subscribe1 received: test async
subscribe2 received: test async
subscribe1 received: test2 async
subscribe2 received: test2 async
于 2019-07-25T08:13:25.887 回答