Problem: I have to fetch both configuration and data from the server. The data can be rendered only after the configuration is fetched and loaded.
How I want my problem solved: I want to fetch both at the same time, using Angular's HttpClient
. However, the callback for configuration must be executed first.
Attempt 1: I tried concat()
from this SO question:
concat(
this.fetchConfig().pipe(take(1)),
this.fetchData().pipe(take(1))
).subscribe(val => {
if (isConfig(val)) {
// This must be executed before the below populate(val);
// This one is slow, blocking, so it must be executed
// as soon as possible.
load(val);
} else {
// val is data
populate(val);
}
});
However, I don't think it accomplishes my goal. I think Observable is a lazy executor, it only executes if there's something subscribe()
to it. concat()
delays the subscription of the callback to fetchData()
, which also delays the actual fetching of data from the server.
Attempt 2: Use forkJoin()
: forkJoin()
only emits once all Observable emitted. The fetching of configuration is usually faster, then I want to execute its callback as soon as possible, so when the data is ready, the configuration may already be fully loaded.
How can I achieve this? And, btw, how can I fix my callback? Have some code to determine if val
is data or configuration is very very ugly.
Edit: I edit the code for more clarification. Basically, I overengineered it. A forkJoin()
should be OK for my case, as load(val)
is pretty fast. However, I still want to push this, by forcing load(val)
to be slow (this is actually what I thought this morning), so it has to be executed as soon as possible AND before populate(val)
.
Right now I'm thinking of making an Observable with it and do chaining.