Rxjs - only first observer can see data from observable .share ()
I have a piece of code as shown below
var videosNeedFix = Rx.Observable.fromArray(JSON.parse(fs.readFileSync("videoEntries.json"))).share();
videosNeedFix.count().subscribe(function(count){ //subscrption A
console.log(count + " in total");
});
videosNeedFix.subscribe(function(videoEntry){ //subscription B
console.log(videoEntry.id, videoEntry.name, videoEntry.customFields);
});
VideoEntries.json is a JSON serialized array of a videoEntry object. I am expecting both subscription A and subscription B to receive data emitted from the video NeedFix observable.
However, according to the console log, only subscription A will get the data, not the subscription. If I change the order of composing two signatures, only the subscription will see information about him. How is it that the observable is only emitting data for the first subscription?
source to share
This is a good use case (and probably the only one - see Use theme or not use theme? ) For Rx.Subject
Consider the following example. This code (with the .delay () hack mentioned in the comments) will work, but it seems a little hacky to me:
let stream$ = Rx.Observable
.return(updatesObj)
.map(obj => Object.assign({}, obj.localData, obj.updates))
.delay(1) //Hacky way of making it work
.share()
stream$
.flatMap(obj => Observable.fromPromise(AsyncStorage.setItem('items', JSON.stringify(obj))))
.catch(Observable.return(false))
.subscribe()
stream$
.subscribe(obj => dispatch(dataIsReady(obj)))
Example with Rx.Subjects:
let subjS = new Rx.Subject()
let stream$ = subjS
.map(obj => Object.assign({}, obj.localData, obj.updates))
.share()
stream$
.flatMap(obj => Observable.fromPromise(AsyncStorage.setItem('items', JSON.stringify(obj))))
.catch(Observable.return(false))
.subscribe()
stream$
.subscribe(obj => dispatch(dataIsReady(obj)))
subjS.onNext(updatesObj)
source to share