I have some code that I am trying to optimize:
someService.subscribeToChanges().subscribe(value => {
const newValue = someArray.find(val => val.id === value.id)
if (newValue) {
if (value.status === 'someStatus') {
someArray.findIndex((a) => a.id === value.id)
someArray.splice(index, 1);
} else {
newValue.status = value.status;
}
} else {
if (value.someProp === 'abc') {
someService.doSomeAsyncStuff().subscribe(data => {
someService.handleData(data);
});
}
}
});
I attempted to refactor the code in order to avoid the second subscribe:
sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
const newValue = someArray.find(val => val.id === value.id)
if (newValue) {
if (value.status === 'someStatus') {
someArray.findIndex((a) => a.id === value.id)
someArray.splice(index, 1);
} else {
newValue.status = value.status;
}
} else {
return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
}
}));
sub$.subscribe(data => someService.handleData(data))
This approach works when the iif
condition is true. However, it halts the stream completely if false, contrary to what I desire which is to keep the stream flowing.