Rx Merge可防止初始值

时间:2017-08-23 12:43:40

标签: system.reactive reactive

我是Reactive开发的新手,我很难以一种能够赋予初始值以及随着时间推移在主题上发生的变化的方式组合多个主题。

使用下面的代码我预计:

first - OnNext(a)  <-- initial on subscribe
first - OnNext(c)  <-- initial on subscribe
first - OnNext(b)  <-- result of OnNext
second - OnNext(b) <-- initial on subscribe
second - OnNext(c) <-- initial on subscribe
first - OnNext(d)  <-- result of OnNext
second - OnNext(d) <-- result of OnNext

但我明白了:

first - OnNext(b)  <-- result of OnNext
first - OnNext(d)  <-- result of OnNext
second - OnNext(d) <-- result of OnNext

代码:

var connection1 = new BehaviorSubject<string>("a");
var connection2 = new BehaviorSubject<string>("c");
var connection = Observable.Merge(connection1, connection2).StartWith(connection1.Value, connection2.Value).Publish();
connection.Connect();
connection.SubscribeLogger("first");
connection1.OnNext("b");
connection.SubscribeLogger("second");
connection2.OnNext("d");

3 个答案:

答案 0 :(得分:2)

Here是一个链接,用于解释Connected Observable背后的一般理想(通过在合并输出上调用Connect()创建。

当调用Connect()时,合并后的输出会将其发布的值发送给订阅者(此时没有,因此初始ac将不会发送给订阅者。

然后first订阅,随后对connection1.OnNext("b");的调用会导致b订阅者显示的first的发布。

接下来,second订阅,但因为它是一个Connected Observable,second只会收到订阅后发布的值。因此,对connection2.OnNext("d");的调用由连接的合并observable发布给其firstsecond的订阅者。

需要花费一些时间和精力来理解通常用于解释反应操作的大理石图。但是,它们提供了一种很好的图形化方式来了解正在发生的事情。

答案 1 :(得分:2)

如果您将代码更改为此...

var connection1 = new BehaviorSubject<string>("a");
var connection2 = new BehaviorSubject<string>("c");
var connection = Observable.Merge(connection1, connection2).StartWith(connection1.Value, connection2.Value).Publish();
connection.SubscribeLogger("first"); //Flip order, put Subscribe before connect
connection.Connect();
connection1.OnNext("b");
connection.SubscribeLogger("second");
connection2.OnNext("d");

然后你会得到这个输出:

first - OnNext(a) //From the start with
first - OnNext(c) //From the start with
first - OnNext(a) //From the behavior subject
first - OnNext(c) //From the behavior subject
first - OnNext(b)
first - OnNext(d)
second - OnNext(d)

Publish / Connect将冷可观察量转换为热可观察量。在您Publish之后,如果您想获得任何&#34; on-subscribe&#34;值,您需要在连接之前订阅。在您Connect之后,没有任何冷或&#34;在订阅&#34;价值将达到新订户。

答案 2 :(得分:0)

此代码似乎可以执行我想要的操作:

var subject1 = new BehaviorSubject<string>("a");
var subject2 = new BehaviorSubject<string>("c");
// Use separate merged observables to simulate multiple calls to getter
// under the hood which builds the new merged view of the subjects.
var connection = subject1.Merge(subject2);
var connection2 = subject1.Merge(subject2);

connection.SubscribeLogger("first");
subject1.OnNext("b");
connection2.SubscribeLogger("second");
subject2.OnNext("d");

输出:

first - OnNext(a)
first - OnNext(c)
first - OnNext(b)
second - OnNext(b)
second - OnNext(c)
first - OnNext(d)
second - OnNext(d)