Rxjs Promise like Observable

2.5k Views Asked by At

I'd like to find a receipt for provide a Promiselike Observable
i mean: that Observable provides a single value and completes,
and any subscriber (before and after completion) should get that single value.
i came out with a combination of Rx.Observable.create publishLast and connect.

var getPromiseLike=function(){
  console.log('getPromiseLike()');
  //// var an_object={}; <--- this should happen inside Obs function
  var prom_like = Rx.Observable.create(function(obs) {
    var an_object={};   /// <--- here !
    setTimeout(function(){
      obs.onNext(an_object);
      obs.onCompleted();
    },500);
  }).publishLast();
  prom_like.connect();
  return prom_like;
};

var promiselike=getPromiseLike();

var obj1;
promiselike
  .subscribe(function(obj){
    console.log('onNext1');
    obj1 = obj;
  },
  function(err){},
  function(){
    console.log('onComplete1');
  });


setTimeout(function(){
  promiselike
    .subscribe(function(obj){
      console.log('onNext2 obj1===obj :'+(obj1===obj)); //true
    },
    function(err){},
    function(){
      console.log('onComplete2');
    });
},1000);

/*LOGS:
getPromiseLike()
script.js:19 onNext1
script.js:24 onComplete1
script.js:31 onNext2 obj1===obj :true
script.js:35 onComplete2
*/

is this the simplest solution or there's some builtin that i missed? plnkr

1

There are 1 best solutions below

6
On BEST ANSWER

In RxJS typically a promise like construct is modeled with AsyncSubject.

It has many of the properties that promises have and is useful:

  • It only receives one value like a promise and will call next only with that value.
  • It caches that value for all future computations.
  • It's a Subject, so it's like a deferred in some promise libraries.

Note: Personally I see no issue with mixing promises with observables, I do it in my own code and Rx plays with promises nicely.