使用 flatMapSingle 时如何避免多次映射器调用

How to avoid multiple mapper calls when using flatMapSingle

假设我有一个 BehaviorProcessor,其中包含一些值 v

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

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

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

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

它会多次打印mapper,这意味着asyncRequest被多次调用,似乎每次其他依赖流被subscribed到

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

有没有办法用标准的 rxjava2 实用程序做到这一点?

使用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