I have a feeling that this question is going to expose some serious naivety surrounding my understanding of observables but at the risk of looking foolish let me ask it anyway.
I would like to create an RXJS subject which does some operations on data passed into it before re-emitting it. Let me explain in longhand using a simplistic example.
e.g. rolling distinctUntilChanged into the source observable
In the code below, I have one observable which is updated every time that an event happens that could alter the window's active state.
However in order to avoid emitting duplicate values I have a second observable which filters only distinct values before emitting them.
export class MyService {
activeValue$ = new Subject<boolean>()
active$: Observable<boolean>
constructor() {
// setup an observable that only emits *changed*
// values of the active value
this.active$ = this.activeValue$.pipe(
distinctUntilChanged()
)
// Listen to multiple cues for things that might alter active state
window?.addEventListener('focus', () => this.setActiveValue(true))
window?.addEventListener('click', () => this.setActiveValue(true))
window?.addEventListener('hide', () => this.setActiveValue(false))
window?.addEventListener('blur', () => this.setActiveValue(false))
}
}
Can I combine the two observables into a single observable?
This example is so simple as to be trivial but it illustrates the goal which is to pre-process the data going into an observable via .next() before re-emitting it.
I would ideally like to be able to write code that looks something like:
export class MyService {
active$: Subject<boolean>
constructor() {
// This (for many reasons) doesn't work but it kind of shows what
// I'm hoping for...
this.active$ = new Subject<boolean>().pipe(
distinctUntilChanged()
)
...
}
}