Rxjs Promise as observable

I would like to find a receipt to receive Promise

, for example Observable


I mean: which Observable

provides one value and completes,
and any caller (before and after completion) should receive 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 are there some built-in ones I missed? plnkr

+3


source to share


1 answer


In RxJS, usually both are modeled as a construct AsyncSubject

.

It has many properties that promises have and are useful:

  • It only gets one value, like a promise, and will call the next one with that value only.
  • It caches this value for all future calculations.
  • This is a topic, so it is similar to the one deferred in some promise libraries.



Note: Personally, I don't see a problem mixing promises with observables, I am doing it in my own code and Rx plays with promises nicely.

+6


source







All Articles