Home > Enterprise >  Unsubscribe Nested Observable when outer observable is false
Unsubscribe Nested Observable when outer observable is false

Time:04-23

I am developing some code where as long as a checkbox is true some inputs will calculate some values and modify other inputs so i came to a solution like this

// boolean observable
this.toggleObservable.subscribe((value)=>{
 if (value) {
this.dataService.calculateValuesObservable.subscribe(...logic that changes the values reactively)
}
})

the problem is when i set the toggle off i cant unsubscribe from calculateValuesObservable

any suggestions?

CodePudding user response:

I would do it like this:

this.dataService.calculateValuesObservable.pipe(
  withLatestFrom(this.toggleObservable), // get the value of toggle
  filter(([toggle, value]) => !!toggle), // only continue with pipe if toggle is true
  map(([toggle, value]) => value)        // transform the result
).subscribe(value => {
   // logic that changes the values reactively
})

You subscribe the calculateValuesObservable and combine it with the latest value of toggleObservable. Afterwards you filter by the value of toggle.

CodePudding user response:

You can use switchMap to unsubscribe from the previous subscription and NEVER to skip when checkbox is disable

import { EMPTY } from 'rxjs';
import { switchMap } from 'rxjs/operators';

this.toggleObservable.pipe(
  switchMap((isChecked) => isChecked
    ? this.dataService.calculateValuesObservable
    : NEVER
  ),
).subscribe((value) => {
  console.log(value);
})
  • Related