I have a subject that subscribes to an event listener Observable (fromEvent). When the button stop is clicked, the subject completes and the event listener should be removed. Currently, I'm keeping track of the subscription and unsubscribe it, which also removes the event listener:
const { fromEvent, Subject } = rxjs
const { map } = rxjs.operators
const subject = new Subject()
subject.subscribe(() => console.log('focused'))
const sub = fromEvent(document.querySelector('input'), 'focus').subscribe(subject)
document.querySelector('button').onclick = () => {
// This is what I would like to avoid
sub.unsubscribe;
subject.complete();
}
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>
<input>
<button>Stop</button>
Is it possible to automatically unsubscribe the subscription sub (and remove the event listener) when subject completes? Something like takeUntilComplete(subject) without installing an additional library.
Edit: The example here is oversimplified. In my real scenario, there is no button that lets the subject complete.