I am new to angular and I struggle with Observables. I searched for my question but I didn’t find an answer for my exact problem.
I’m trying to enable/disable keyboard events depending on a variable (Observable) I get from the store.
...
isDisabled$: Observable<boolean> = this.store.select(selectIsDisabled);
private subscriptions = new Subscription();
constructor(
private store: Store<IStore>
) {
this.onKeyboardEvent();
}
...
// this.subscriptions is used in other functions
...
private onKeyboardEvent(): void {
let keys: string[] = [];
this.subscriptions.add(
fromEvent<KeyboardEvent>(document, 'keydown').pipe(
filter(key => key.repeat === false),
map(key => key.code)
).subscribe(keyCode => {
if (!keys.includes(keyCode)) {
keys.push(keyCode);
}
// Here we have keys pressed logic...
})
);
}
Here is my code now, what I want to achieve is to enable/disable keyboard events depending on isDisabled$
value (I have a button to change isDisabled$ value).
I tried to subscribe to isDisabled$
and call this.onKeyboardEvent()
when isDisabled is false but the problem is this.subscriptions still have fromEvent
event even when isDisabled is true.
I tried also to unsubscribe this.subscriptions
when isDisabled === true but this didn’t work for me
I am new to angular & rxjs I don’t know if there’s an operator to achieve this?
Thanks for your help 🙂