Home > other >  How to toggle rxjs variable?
How to toggle rxjs variable?

Time:10-14

How correct is it to do a toggle variable?

public toggleLabels$ = new BehaviorSubject<boolean>(true);

public toggleLabels() {
    this.toggleLabels$.next(!this.toggleLabels$.getValue());
}

I just get reverse value and push it back. Is it good way?

CodePudding user response:

With scan RxJS has a built in state managing solution that can be used for all state scenarios.

Useful for encapsulating and managing state. Applies an accumulator (or "reducer function") to each value from the source after an initial state is established -- either via a seed value (second argument), or from the first value from the source.

const { Subject } = rxjs;
const { scan, startWith } = rxjs.operators;

const toggle$$ = new Subject();

const toggle$ = toggle$$.pipe(
  scan((state, curr) => !state, true),
  startWith(true)
);

toggle$.subscribe(console.log)

toggle$$.next();
toggle$$.next();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.4.0/rxjs.umd.min.js"></script>

CodePudding user response:

this is fine for something this simple but getValue() isn't something I'd make a habit of using. it can get messy and break in more complex situations.

you generally want to keep state modifications inside the observable to make sure everything happens in the order it's supposed to.

here's how you could do that:

// two subjects, one for saving state, one for signaling toggles
private toggleSource = new Subject();
private toggleLabelsSource = new BehaviorSubject<boolean>(true);
// keep state observables private
toggleLabels$ = this.toggleLabelsSource.asObservable();

constructor() { 
  // link observables
  this.toggleSource.pipe(
    scan((toggle, _) => !toggle, true)
  ).subscribe(this.toggleLabels$);
}

public toggleLabels() {
  // call next on toggle signal.
  this.toggleSource.next(null);
}

this is overly complex for something so simple, but the pattern makes more sense when you're dealing with more complicated state transformations.

CodePudding user response:

Create a service that contains:

  private toggleValue = true;
  private toggleLabelsSource = new BehaviorSubject<boolean>(this.toggleValue);
  currentToggleLabels = this.toggleLabelsSource.asObservable();


  toggleLabels(): void {
    this.toggleValue = !this.toggleValue;
    this.toggleLabelsSource.next(this.toggleValue);
  }

Then you can listen to currentToggleLabels and toggle through toggleLabels()

  • Related