简体   繁体   English

RxJava:为多个 Observable 使用相同的 Observer 调用 .subscribe()

[英]RxJava: Calling .subscribe() with same Observer for multiple Observables

What is the behavior of the same Observer calling .subscribe() on several Observables?同一个 Observer 在多个 Observable 上调用.subscribe()的行为是什么?

Will they be implicitly merged?它们会被隐式合并吗? Or is it that that last on wins?或者是最后一次获胜?

For instance:例如:

event1.subscribe(myObserver);
event2.subscribe(myObserver);

Based on the javadoc , as long as you don't cancel the Subscription s returned by each Observables, the observer will be subscribed to all observables .根据javadoc ,只要不取消每个 Observable 返回的Subscription ,观察者就会订阅所有 observable

I expect if you subscribe the same observer multiple times to one observable, you will be notified multiple times - otherwise the subscriptions made previously would "magically" go dead, which is something that may cause troubles.我希望如果您多次订阅同一个观察者到一个 observable,您将多次收到通知 - 否则之前进行的订阅会“神奇地”消失,这可能会导致麻烦。

// data members
Observable x, y;

void foo(Subscriber a) {
  // is subscriber a already registered with x?
  // Nevermind, I'm gonna make sure it is!
  Subscription s=x.subscribe(a);
  // provoke a change to be caught by 'a'

  // do some work based on whatever Subscriber 'a' captured.

  s.unsubscribe();
}

void bar() {
  Subscriber m;
  Subscription mx=x.subscribe(m);
  Subscription my=y.subscribe(m);

  // do something and then...
  foo(mx); // one would expect the mx subscription is still valid here!!!
  // do some more work

  my.unsubscribe();
  mx.unsubscribe();
}

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

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