Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Observable of type boolean?

I need to create an Observable that emits a booleand and can be changed from a function.

I tried

showModal$ = new Observable<boolean>();

But it does't works.

What I need is showModal$ to be false by default. And change its value with a function

change() {
  this.showModal$ = !this.showModal$;
}

I'm using Angular2 and I want to subscribe to that Observable from differents components.

What's the best way to do this?

like image 404
akko Avatar asked Oct 30 '25 06:10

akko


1 Answers

Use a BehaviorSubject

showModal$ = new BehaviorSubject<boolean>(false);

change() {
  this.showModal$.next(!this.showModal$.getValue());
}

Here is a JavaScript demo

const { BehaviorSubject, fromEvent } = rxjs;

const showModal$ = new BehaviorSubject(false);

function change() {
  showModal$.next(!showModal$.getValue());
}

fromEvent(document.getElementById('change'), 'click').subscribe(_ => {
  change();
});

showModal$.subscribe(showModal => {
  console.log(`Modal is shown is ${showModal}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>
<button id="change">Change</button>
like image 71
Adrian Brand Avatar answered Oct 31 '25 20:10

Adrian Brand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!