As I am already quite experienced developer in .NET, I am learning new technologies and I am curious how would you resolve this problem in TypeScript + RxJS. Let's say, I have a multiple columns (fields) and I am observing their value changes. I also have a switch which has groups of columns to observe - in this example 1, 2, 3; A, B, C and X, Y, Z.
Every time I have to switch, I would like to remove subscriptions from previous group, and create for new one. The code looks like that:
const log = (cid: string) => console.info(`${cid} changed`);
this.subscriptions.add(this.observeValueChanges("column 1").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column 2").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column 3").subscribe(log));
//Switching to another columns collection - I don't want previous subscriptions anymore
this.subscriptions.unsubscribe();
this.subscriptions.add(this.observeValueChanges("column A").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column B").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column C").subscribe(log));
//Switching to another columns collection - I don't want previous subscriptions anymore
this.subscriptions.unsubscribe();
this.subscriptions.add(this.observeValueChanges("column X").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column Y").subscribe(log));
this.subscriptions.add(this.observeValueChanges("column Z").subscribe(log));
for reference:
private subscriptions: Subscription = new Subscription();
and
observeValueChanges(columnId: string): Observable<any> {
return timer(0, 1000).pipe(map(_ => columnId), publish(), refCount());
}
I can make it working by substituting subscription object by array of subscriptions, and after switching - I can unsubscribe all from array (and instead of add - I can push). What do you thing? I have no problem with making "switch signal" as observable.
