Rx java2 使用flatMapSingle时如何避免多个映射器调用
假设我有一个Rx java2 使用flatMapSingle时如何避免多个映射器调用,rx-java2,rx-kotlin2,Rx Java2,Rx Kotlin2,假设我有一个行为处理器,它包含一些值v 现在,如果我想异步请求一些数据,这取决于v,我会这样做: val res = v.flatMapSingle { asyncRequest(it) } 现在让我们记录这个块的所有调用(映射器) 它将多次打印mapper,这意味着asyncRequest被多次调用,似乎每次都有其他依赖流被subscribed调用 我试图避免多次映射器调用(从而避免多次asyncRequest调用) 有没有一种方法可以使用标准的rxjava2 UTIL实现这一点?使用cac
行为处理器
,它包含一些值v
现在,如果我想异步请求一些数据,这取决于v
,我会这样做:
val res = v.flatMapSingle { asyncRequest(it) }
现在让我们记录这个块的所有调用(映射器)
它将多次打印mapper
,这意味着asyncRequest
被多次调用,似乎每次都有其他依赖流被subscribe
d调用
我试图避免多次映射器调用(从而避免多次asyncRequest
调用)
有没有一种方法可以使用标准的rxjava2 UTIL实现这一点?使用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");
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