41100

Rxjs - only the first observer can see data from observable.share()

Question:

I have some code snippet as following

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); });

The videoEntries.json is a JSON-serialized array of videoEntry object. I'm expecting both subscription A and subscription B to receive the data emitted by videosNeedFix observable.

However, according to the console log, only the subscription A will receive data but not the subscriptionB. If I swap the order of making the two subscriptions, only subscriptionB will see the data. How come the observable only emits data to the first subscription?

Answer1:

This is a good use case (and maybe the only - see <a href="http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx" rel="nofollow">To Use Subject Or Not To Use Subject?</a>) for a Rx.Subject

Consider the following example. This code (with .delay() hack mentioned in the comments) will work, but seems a bit 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)

Recommend

  • passing array values into a function
  • Doctrine2 + Symfony2 Keeping history on every insert, update, delete
  • php accessing attributes in json
  • preselecting a value based on URL with javascript
  • How enable GZIP compression for Spring HttpInvoker requests using Tomcat?
  • Json.net Add property to every class containing of a certain type
  • How to remove coupon from Stripe plan w/ Laravel Cashier 4
  • How to obtain dynamic google map url of a specific map (I have static map url)
  • Selection sort growing ordered ranges from both ends
  • How to read/write integer values from bytes without old_io?
  • Loading a TGA File and Using it with OpenGL
  • Pubnub subscribe stops receiving messages after some time
  • Defining Tables, Views, and Indexes in AWS CloudFormation
  • C++ exception safety paranoia: how much is too much?
  • Gson serializing Spring beans
  • How do I create shared library using ld?
  • Disable add to cart redirection
  • Selection Sort, For Java
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • SQL: Getting the physical size of a subset of a table
  • What is the difference between a “service account” and an “installed application”?
  • pip in virtualenv gets ConnectTimeoutError
  • Marklogic : Query response time is very high
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • jquery mobile loadPage not working
  • Rearranging Cells in UITableView Bug & Saving Changes
  • AT Commands to Send SMS not working in Windows 8.1
  • File upload with ng-file-upload throwing error
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • AngularJs get employee from factory
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Proper way to use connect-multiparty with express.js?
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • How do I configure my settings file to work with unit tests?
  • How to stop GridView from loading again when I press back button?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?