Home > Software design >  How can I merge parent and child observablein rxjs
How can I merge parent and child observablein rxjs

Time:01-19

I have created a parent observable with a child observable. When the child observable completes it completes the parent observable.

Is there a nicer way to do this without having to use subscripe() twice.

Code:

const parentObservable = new Observable((observer) => {
  
  if (condition) {
     observer.complete();
     return;
  }

  this.childObservable().subscribe(() => observer.complete());
});

parentObservable.subscribe();

EDIT: We want to be able to not subscribe to the child if a condition is met

CodePudding user response:

The merge operator allows you to merge multiple observables into a single observable. You can use this operator to merge the parent observable and the child observable.

const parentObservable = new Observable((observer) => {
  // random sync code
});

const childObservable = this.childObservable();

merge(parentObservable, childObservable).subscribe();

If you want to complete the parent observable when the child observable completes, you can use the concat operator instead. The concat operator will emit the values from the first observable, and then emit the values from the second observable once the first observable completes.

import { concat } from 'rxjs';

const combinedObservable = concat(parentObservable, childObservable);
combinedObservable.subscribe();

This will complete the parent observable when the child observable completes.

merge operator combines all the observables into a single stream and emits value as they come.

concat operator concatenate the observables and emits value only after the first observable completes.

CodePudding user response:

According to your description

When the child observable completes it completes the parent observable.

I believe you could use takeUntil.

const parentObservable = new Observable((observer) => { ... });

parentObservable.pipe(takeUntil(childObservable)).subscribe();

Whenever childObservable emits a value the pipe will complete and the teardown logic of parentObservable (if there is one) will be run.


  • Related