The-the-publish (or multicast with a RxJS Subject) makes the shared Observable not reusable if the shared execut Ion happens to complete or emit an error. In this lesson we'll see how to use a simple Subject factory function in order to create a new Subject, one for each SHA Red execution, whenever connect () is called.
var shared = Rx.Observable.interval (+). Take (3) . Do (x = Console.log (" + x)") . Multicast (new rx.subject ()) . RefCount ();
The code above, after subject emit 0,1,2, three values, then it completes. It means if you want to subscribe the subject again, it won ' t emit anything because it is completed.
If you want to reuse the ' gkfx ' subject even after subject complete, you need to use subject factories, which simply jus T a function return new Subject ():
function Subjectfactory () { returnnew rx.subject ();} var shared = Rx.Observable.interval (+). Take (3) . Do (x = Console.log (" + x)") . Multicast (subjectfactory) . RefCount ();
So now even your resubscribe after subject complete, it'll emit you new value.
function Subjectfactory () {return Newrx.subject ();}varShared = Rx.Observable.interval ( +). Take (3) . Do(x = Console.log ('Source'+x). Multicast (subjectfactory). RefCount ();//Subject:--0--1--2--3--4--5|//A//subject2:--0--1--2--3--4--5|varObservera ={next:function (x) {Console.log ('A Next'+x); }, Error:function (err) {Console.log ('A Error'+err); }, Complete:function () {Console.log ('A Done'); },};varSubA = Shared.subscribe (Observera);//0 = 1Console.log ('subscribed A');varObserverb ={next:function (x) {Console.log ('B Next'+x); }, Error:function (err) {Console.log ('B Error'+err); }, Complete:function () {Console.log ('B Done'); },};varsubb;settimeout (function () {Subb=Shared.subscribe (Observerb); Console.log ('subscribed B');}, -); SetTimeout (function () {suba.unsubscribe (); Console.log ('unsubscribed A');}, the); SetTimeout (function () {subb.unsubscribe (); Console.log ('unsubscribed B');}, the); SetTimeout (function () {SubA= Shared.subscribe (Observera);//0 = 1 (connect)Console.log ('subscribed A');}, 6000);
/* * "subscribed A" "Source 0" "A Next 0" "Source 1" "A Next 1" "Subscribed B" "Source 2" "A Next 2" "B Next 2" "A Done" "B" "un" Subscribed a "" Unsubscribed B "" Subscribed a "" Source 0 "" A Next 0 "" Source 1 "" A Next 1 "" Source 2 "" A Next 2 "" A Done "*/
[RxJS] Reusable multicasting with Subject factories