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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With