Rx Reactive Streams可连接的Observables

时间:2015-07-28 06:01:23

标签: java scala reactive-programming subscription observable

阅读本文件:

https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators

我有一些问题可以管理Connectable Observables的工作规则!这就是Wiki中解释的内容:

The following example code shows two Subscribers subscribing to the same Observable. In the first case, they subscribe to an ordinary Observable; in the second case, they subscribe to a Connectable Observable that only connects after both Subscribers subscribe. Note the difference in the output: 

Example #1:

def firstMillion  = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS);

firstMillion.subscribe(
   { println("Subscriber #1:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #1 complete"); }       // onCompleted
);

firstMillion.subscribe(
    { println("Subscriber #2:" + it); },       // onNext
    { println("Error: " + it.getMessage()); }, // onError
    { println("Sequence #2 complete"); }       // onCompleted
);
Subscriber #1:211128
Subscriber #1:411633
Subscriber #1:629605
Subscriber #1:841903
Sequence #1 complete
Subscriber #2:244776
Subscriber #2:431416
Subscriber #2:621647
Subscriber #2:826996
Sequence #2 complete

Example #2:

def firstMillion  = Observable.range( 1, 1000000 ).sample(7, java.util.concurrent.TimeUnit.MILLISECONDS).publish();

firstMillion.subscribe(
   { println("Subscriber #1:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #1 complete"); }       // onCompleted
);

firstMillion.subscribe(
   { println("Subscriber #2:" + it); },       // onNext
   { println("Error: " + it.getMessage()); }, // onError
   { println("Sequence #2 complete"); }       // onCompleted
);

firstMillion.connect();
Subscriber #2:208683
Subscriber #1:208683
Subscriber #2:432509
Subscriber #1:432509
Subscriber #2:644270
Subscriber #1:644270
Subscriber #2:887885
Subscriber #1:887885
Sequence #2 complete
Sequence #1 complete

我没有得到以下内容:

  1. 在示例#2中,Observable将如何知道有两个订阅者(在这种情况下)

  2. 如何处理其中一个订阅者很慢的情况。

1 个答案:

答案 0 :(得分:0)

回答您的第一个问题:因为拨打了subscribe两次。

回答你的第二个问题:如果这是一个问题,你需要对观察者应用一些背压算法,这可能会很慢。

RxJS回购对RxJS中的某些背压选项有good introduction。我不确定RxJava中存在多少提及的运算符。我知道其中有些人会这样做。