Combine consecutive observables

Viewed 176

My problem is to combine two consecutive observables and return it as a single observable. There are a lot of combine operators in rxjs but documentation just confused me.

Here is a working solution I came up with. However, I feel like it isn't the right way to do it for readability.

const observableGetId = () => {SomeFunctionBody};
const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};

observableGetId.pipe(
  mergeMap((id) => {
    return forkJoin([
      of(id),
      observableGetDataWithId(id)
    ])
  })
).subscribe((result) => {
  console.log(result[0]) // id
  console.log(result[1]) // data
})

Is there a better operator or some other way to do this?

2 Answers

I believe you want to get {id: processedId, data: data for relevant Id} in a simple way.

You can do following,

const observableGetId = () => {SomeFunctionBody};
const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};

observableGetId.pipe(
  mergeMap((id) => observableGetDataWithId(id).pipe(
    map(res => {return {id: id, data: res}})
)))
.subscribe((result) => {
    // console.log(result.id, result.data);
})

You can do that with SwitchMap, which is actually an efficient way while you can also add error handling part with help of catchError.

  const observableGetId = () => {SomeFunctionBody};
  const observableGetDataWithId = (id) => {SomeAnotherFunctionBody};

  observableGetId.pipe(
      switchMap((id)=> observableGetDataWithId(id).pipe(
        map(res => {return {id: id, data: res}}))
      catchError(err => of(null)))
   ).subscribe((result) => {
           console.log(result.id, result.data);
   }, error => 
         console.log("Error Description");
   );

Also look at the below article for better understanding about RXJS operators.

Happy Coding.. :)

Related