I have developed a component that contains two buttons (searchButton
, lazyButton
). The ngOnDestroy
method is defined as follows:
public ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
I have created two observables from the click events of these two buttons:
this.eager$ = Rx.Observable.fromEvent(this.searchButton, 'click')
.takeUntil(this.$unsubscribe);
this.lazy$ = Rx.Observable.fromEvent(this.lazyButton, 'click')
.takeUntil(this.$unsubscribe);
Thus, when the component is destroyed, both observables are automatically unsubscribed.
However, every time a button is clicked, I need to make an HTTP request:
Observable
.merge(this.eager$, this.lazy$)
.switchMap(() => this.service.getItemsFromStorage())
Now, I receive an Observable<Response>
which requires me to handle the response:
Observable
.merge(this.eager$, this.lazy$)
.switchMap(() => this.service.getItemsFromStorage())
.map(response => response.json())
.map(page => <Array<AdministrationUser>>page.included)
After these transformations, I obtain an
Observable<Array<AdministrationUser>>
.
Next, I need to apply certain modifications on each AdministrationUser
. Therefore, I create an
Observable<AdministrationUser>
:
Observable
.merge(this.eager$, this.lazy$)
.switchMap(() => this.service.getItemsFromStorage())
.map(response => response.json())
.map(page => <Array<AdministrationUser>>page.included)
.switchMap(page => Observable.from(page.users))
Once the users are obtained, I can modify each user individually:
Observable
.merge(this.eager$, this.lazy$)
.switchMap(() => this.service.getItemsFromStorage())
.map(response => response.json())
.map(page => <Array<AdministrationUser>>page.included)
.switchMap(page => Observable.from(page.users))
.do(user => /*modify user*/)
Finally, all modified users need to be collected together again:
Observable
.merge(this.eager$, this.lazy$)
.switchMap(() => this.service.getItemsFromStorage())
.map(response => response.json())
.map(page => <Array<AdministrationUser>>page.included)
.switchMap(page => Observable.from(page.users))
.do(user => /*modify user*/)
.reduce((acc, value) => [...acc, value], [])
.do(users => this.rowsToShow = [...users])
.takeUntil(this.unsubscribe$)
.subscribe();
Despite this approach, the code at (&&$$&&)
does not seem to execute.
This could possibly be due to the behavior of the reduce
method, which waits for the observable to end. However, in this case, the observable switches to an array of elements once the HTTP response is received through
.switchMap(page => Observable.from(page.users))
. This should lead to the observable ending when all elements of the array are processed.
Do you have any suggestions or ideas on how to resolve this issue?