简体   繁体   English

Java Project Reactor subscribeOn Mono 链的行为

[英]Java Project Reactor subscribeOn behavior for Mono chains

I am learning about project reactor and get confused on some questions regarding subscribeOn()我正在学习项目反应堆,并对有关 subscribeOn() 的一些问题感到困惑

My blocking code looks like (say getA(), getB(), getC(A, B), getD(A, B), getE(C, D) are both time complex functions)我的阻塞代码看起来像(比如getA(),getB(),getC(A,B),getD(A,B),getE(C,D)都是时间复杂函数)

public E someMethod() {
  A a = getA();
  B b = getB();
  C c = getC(a, b);
  D d = getD(a, b);
  return getE(c, d);
}

Now I want to change it into a unblocking implementation, I wrote现在我想把它改成一个畅通的实现,我写了

public E someMethodUnblocking() {
  Mono<A> a = Mono.fromCallable(getA).subscribeOn(Schedulers.boundedElastic());
  Mono<B> b = Mono.fromCallable(getB).subscribeOn(Schedulers.boundedElastic());
  Mono<C> c = Mono.zip(a, b, (aa, bb) -> getC(aa,bb)).subscribeOn(Schedulers.boundedElastic());
  Mono<D> d = Mono.zip(a, b, (aa, bb) -> getD(aa,bb)).subscribeOn(Schedulers.boundedElastic());
  return Mono.zip(c, d, (cc, dd) -> getE(cc, dd)).block()
}

Does this look like the correct implementation?这看起来像正确的实现吗? will there be a difference if I remove the subscribeOn() when generating Mono a and b?如果我在生成 Mono a 和 b 时删除 subscribeOn() 会有区别吗?

Your implementation subscribes twice to the (cold) monos a and b - and will run your costly getA() and getB() methods two times.您的实现两次订阅(冷)单声道 a 和 b - 并将运行您昂贵的 getA() 和 getB() 方法两次。

To avoid that, you should cache() the first two monos.为避免这种情况,您应该 cache() 前两个单声道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM