1

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}`))
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • This is very very similar to [How do I access previous promise results in a `.then()` chain?](http://stackoverflow.com/q/28250680/1048572). Especially since your observables seem to behave like promises (single-result). – Bergi Mar 08 '16 at 18:54

2 Answers2

1

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.

jamesRH
  • 420
  • 3
  • 12
1

You can create a closure to store the user and then use flatMapLatest to emit the user and directory result:

let ensureUser$ = ghUser$
  .flatMapLatest(user => {
      return Rx.Observable.fromPromise(createDir(u))
           // Emit the directory and user information
           .map(directory => ({ directory, user }));
  })
  .do((x) => debug('created', x))
Calvin Belden
  • 3,114
  • 1
  • 19
  • 21