Ivan Petrov
Ivan Petrov

Reputation: 37

How to make an async pipe in rxjs@5?

How to make something similar to the code below?

.map( async request => await asyncRequest( request ) )  

Event click collect data and create a request object. Then call .next( request ). How do I get [object Promise], and json?

let a = Rx.Observable.create( observer => {
  Rx.Observable.fromEvent(document, 'click')
  .do( () => observer.next(  ) )
  .subscribe( result => console.log(`[a] complete`), error => console.log(`a error: ${error}`));
} );


function asyncRequest( request ) {
  return Rx.Observable.create( observer => {
    new Promise( ( resolve, reject ) => {
      setTimeout( ( ) => resolve( 'response' ), 1000 );
    } )
  } )
}

a
  .map( request => asyncRequest( request ) )
  .do( json => console.log(json) ) // to get json
  .subscribe( result => console.log(`complete: ${result}`) )

Upvotes: 1

Views: 476

Answers (1)

paulpdaniels
paulpdaniels

Reputation: 18663

You should use flatMap instead of map

let a = 
  Rx.Observable.fromEvent(document, 'click')
    //Console loggin is a side effect, so make it the do instead of 
    //wrapping the Observable
    .do(_ => console.log(`[a] complete`), 
        error => console.log(`a error: ${error}`));


function asyncRequest( request ) {
  //This will actually handle the result of the Promise
  return Rx.Observable.defer(() => 
    new Promise( ( resolve, reject ) => {
      setTimeout( ( ) => resolve( 'response' ), 1000 );
    })
  );
}

a
  //Kicks off an async request each time an event comes in
  //and then flattens the response into the stream.
  .flatMap(asyncRequest)
  .do( json => console.log(json) ) // to get json
  .subscribe( result => console.log(`complete: ${result}`) )

Upvotes: 2

Related Questions