Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a stream of Promises into a stream of values

Tags:

promise

rxjs

I am somewhat new to RxJs and I am trying to mix the world of promises and observables.

Here is what I want: I have an observable (call it clickObs) which listens to a click and as a result interrogates a database, producing a promise which resolves to a value when the database querying concludes (successfully). My observable thus generates a stream of promises from a stream of clicks, and what I want is to generate from that observable, a stream of corresponding resolved values.

From past questions on stackoverflow, I read about defer, flatMap, mergeAll, and fromPromise, but cannot get my head around how to articulate the four to solve my problem.

Any suggestions?

like image 547
user3743222 Avatar asked Oct 20 '22 06:10

user3743222


1 Answers

You shouldn't need all four, just look at flatMap or its sibling flatMapLatest

clickObs.flatMapLatest(function() {
  //Access the db and return a promis
  return database.query(queryObj);
})
.subscribe(function(result) {
  //Result is implicitly flattened out
  /*Do something with the result*/
});

flatMap will implicitly convert a promise or array-like object into an Observable and flatten out the resulting sequence. FlatMapLatest is similar but will ignore old events, if a newer one arrives before the previous one completed.

like image 151
paulpdaniels Avatar answered Oct 27 '22 11:10

paulpdaniels