Search code examples
javascriptrxjsreactive-extensions-js

Access variables later in the chain


In the example below I'm taking a user and creating a directory for that user. I want to simply log that the user as been created. What's the best way to get access to the user variable later in the chain?

let ensureUser$ = ghUser$
  .map(u => Rx.Observable.fromPromise(createDir(u)))
  .flatMapLatest(x => x)
  .do(() => debug('created user dir'))

I want to do something like:

let ensureUser$ = ghUser$
  .map(u => Rx.Observable.fromPromise(createDir(u)))
  .flatMapLatest(x => x)
  .do(() => debug(`created user dir ${u}`))

Solution

  • You could do something like this with zip since zip will only returns a new object when it has all new data.

    const user$ = Rx.Observable.just('ed')
    const returnedArrary$ = user$.map(u=>[u]);
    
    const source = Rx.Observable.zip(
        user$,
        returnedArrary$
      )
     .do(u=>console.log(`created user dir ${u[0]}`))
     .subscribe((x)=>console.log(x));
    

    if the user does not change with every request you could you withLatestFrom or combineLatest depending on your needs.