BehaviorSubject initial value not working with share ()

Operator

share() applies to Behavior. BehaviorSubject has an initial value.

The goal is to create a single shared subscription. But this joint subscription email does not work when BehaviorSubject has an initial value.

Getting unexpected results.

The code shown below:

 let subject = new Rx.BehaviorSubject(0); let published = subject .do(v => console.log("side effect")) .share(); published.subscribe((v) => console.log(v+" sub1")); published.subscribe((v) => console.log(v+" sub2")); subject.next(1); 

Result:

 "side effect" "0 sub1" "side effect" "1 sub1" "1 sub2" 

Expected Result:

 "side effect" "0 sub1" "1 sub1" <------------- this is missing from actual result "side effect" "1 sub1" "1 sub2" 
+5
source share
1 answer

I understand that it is not clear.

BehaviorSubject emitted only by subscription. However, you use the share() operator, which internally is a shorthand for publish()->refCount() . When the first observer subscribes, it starts refCount() and subscribes to its source, which causes a side effect in do() , and also prints the default value in observer 0 sub1 :

 "side effect" "0 sub1" 

Then you subscribe with another observer, but this subscription is done only in the Subject class inside the publish() statement (for which it did). Thus, the second observer will not get a default of 0 and does not activate a side effect.

When you later call subject.next(1) , it will output the last three lines of output:

 "side effect" "1 sub1" "1 sub2" 
+5
source

Source: https://habr.com/ru/post/1265529/


All Articles