So, I'm trying to wrap my head around rxjs/observable
, in my test-case study I'm trying to build a simple angular(5) based web-app that should display some stats about geo entities, namely country, state, city. So I've crated changeView
method that accepts three parameters(two optional) with respective ids.
At the beginning I wanted the app initially to check in my model if the country data is already loaded, if not then query the data, to save the retrieved data in the model, then to check if the stateId
was specified and is included in country.states
array then to check if already loaded, if not to query for the state and so on, until all the data was retrieved, or user has changed the input parameters, in that case all ongoing requests should stop(as far as I understood this part is done by switchMap
operator), and new round of request should start. After couple of days I've understood that this is too complicated, so I've changed the plan and decided to store the data into the model only at the end. And it looks like it does what I intended to, but the sub-sequential requests are not being cancelled. Following is an excerpt from what I currently have:
of({countryId: 1, stateId: 1, cityId: 1}).pipe(
debounceTime(500),
switchMap(newState => {
if ((newState !== null))
{
return this.geoStatsService.getCountry(newState.countryId);
}
else
{
return empty();
}
}, (outerValue, innerValue) => {
if ("stateId" in outerValue && outerValue.stateId !== undefined)
{
// ToDo: Check that state is located in this county
return forkJoin(of(innerValue), this.geoStatsService.getStates(outerValue.stateId));
}
else
{
return of(innerValue);
}
}),
mergeAll()
).subscribe(res => {
console.debug("---Subscription---");
console.debug(res);
});
I've seen that once the second request was fired, it won't be cancelled and the data will get to the subscription... It looks to me like I'm over-complicating it, and it could be done in more elegant way, which also will work as I intended, is it so? Additional question: Can I, or more precise question - should I extract the data from within the flow, or only in subscription method?