im wondering how we can wait on a reosurce to be loaded (because its loaded in a resolver)
I simplified the example and added comments for use cases.
The example shows getBySerialNumber being called from a resolver
I havent testet it yet, but I added a while loop, to wait for the resource to complete. And was hoping someone might has a better idea.
Another idea I have, which I would like feedback on is: make the function async, and use the http client directy, and then set the resource manually. However I im not sure thats a good approach. I think its better than the while loop tho
machine.api.ts
private readonly machineResource: ResourceRef<Machine[]> = rxResource({
stream: () => {
// use-case: we need them eagerly loaded (compared to toSignal())
return (this.httpClient.get<MachineResponseDto[]>(this.baseUrl + 'GetAllMachines'));
},
defaultValue: [],
});
reloadMachines(): void {
if (!this.machineResource.reload())
console.warn('unnecessary or unsupported reload call on get all machines skipped.');
}
// this method is called in a resolver, so we can make it async or use Obersavles if needed
getBySerialNumber(serialNumber: string): Machine | null {
const getBySerialNo = () =>
untracked(this.machineResource.value).find(
(m) => m.serialNumber === serialNumber,
) ?? null;
const machine = getBySerialNo();
if (machine) return machine; // hot path first
this.reloadMachines(); // unlikely usecase, because to view a machine you'd have to click on it on the dashboard, where it was already loaded
while (this.machineResource.isLoading()) {
// wait for the resource to be loaded
// blocking the ui is fine, because its white currently anyways, if this is called from the resolver
}
return getBySerialNo();
}