Thibs
Thibs

Reputation: 8288

Angular & RxJS5 - updating data from http & socket

I have a scenario where I need to:

  1. Get route params
  2. Use route params to call http service
  3. Once http responds, use same route params to call a socket service
  4. Each time socket responds, update data from http service

Ideally I would like to keep this in a stream.

If only I could use CombineLatest? or involve the Scan operator?

this.data$ = this.route.params
               .switchMap(params => {
                   return Observable.forkJoin([
                       Observable.of(params),
                       this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
                   ])
               }).combineLatest(([params, data]) => {
                    this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }),
                        updateData
                })


    private updateData(data, socketData): any[] {
        //only returns data = [params, data]
        //socketData always undef
        return data;
    }

Upvotes: 0

Views: 71

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

From how I understood your flow I don't need you need any of the combineLatest or scan operators, you just need to nest two switchMaps:

this.data$ = this.route.params
                .switchMap(params => this.http.get('api', { prop1: params.prop1, prop2: params.prop2 })
                    .switchMap(httpResult => this.socket.get('event', { prop1: params.prop1, prop2: params.prop2 }) // assuming socket.get(...) is a perpetual stream
                        .map(socketResult => doWhateverCombinationWith(httpResult, socketResult))
                        .startWith(httpResult); // not sure if this is required, your question is kind of vague, but essentially this will cause the stream to emit the original httpResult before there is socketData
                    )
                );

Upvotes: 1

Related Questions