Let's explore a different use of the multicast () operator in RxJS, where can provide a selector function as a sandbox The where the shared Observable is available.
When we have the code like below:
var result = Rx.Observable.interval (1000 ). Take (6 ). do (x = Console.log ( ' + X"). Map (x => Math.random ()); var Delayedresult = result.delay (500 Span style= "color: #000000;" >); var merged = Result.merge (Delayedresult); Merged.subscribe ((x) = Console.log (x))
/* "Source 0" 0.5832993222895915 "source 0" 0.031394357976560316 "Source 1" 0.27602687148865 "Source 1" 0.8762531748833942 "Source 2" 0.49254272653868103 "Source 2" 0.8024593359949526 ... */
You can notice this, it runs ' result ' block twice each time, it because ' merged ' subscribe to ' result ' and ' Delayedresult ' Also subscribe to ' result ', therefore it logs out source twice.
If you are want one subscribe, you can use multicast (), with a second param which is sandbox function.
Normally you'll use Mulitcast () with RefCount ():
function Subjectfactory () { returnnew rx.subject ();} var result = Rx.Observable.interval (+). Take (6) . Do (x = Console.log (' + x)) = math.random ()) . Multicast (subjectfactory). RefCount (); var sub = result.subscribe (x = Console.log (x));
If you pass a second param:
var result = Rx.Observable.interval (1000 ). Take (6 ). do (x = Console.log ( ' ' + x '). Map (x => Math.random ()). Multicast (subjectfactory, function sandbox (shared) { var delayedshare = Shared.delay (500 ); var merged = Shared.merge (Delayedshare) ; return merged; });
Result.subscribe (x = Console.log (x));
/* "Source 0" 0.92148611490954790.9214861149095479 "Source 1" 0.16849192186775230.1684919218677523 "Source 2" 0.281828766896897950.28182876689689795...* *
Notice that, are you pass a second param to Multicase () and the return value is no longer an connectableobservable. It is just a normal observable. Cannot call ' refcount () ' anymore.
and inside Sandbox () function, you need to retrun a observable.
From the results can see, we no longer subscribe the source twice.
The takeaway is your should use a function in if you selector
multicast
are want to create and let's say, a diamond-shaped dependency. Here we have a bifurcation. As we have shared, and it's used in the parts, and then we converge those the parts together to return one Observa ble. That's kind of a diamond shape, where we bifurcate, and then we converge.
That's one case where you almost always want selector
-a function in multicast
. If you don ' t, then usually we use just with multicast
a refCount
. That's quite common to use.
[RxJS] Multicast with a selector argument, as a sandbox