StephenCleary / AsyncEx

A helper library for async/await.
MIT License
3.49k stars 358 forks source link

AsyncLazy with API call is being called twice across 4 components. #284

Closed dartuso closed 6 months ago

dartuso commented 6 months ago

I am using AsyncLazy in a shared class between multiple blazor components, which all want the data OnInitializedAsync

As show in this blog I am replicating the structure of data caching

https://blog.stephencleary.com/2013/01/async-oop-3-properties.html In API class

    API(){
            LazyVariable= new AsyncLazy<DTO>(async () =>
            {
                string url = $"url";
                var response =  await httpClient.GetFromJsonAsync<DTO>(url);
                AppState.var = response; 
                return response;
            });
     }

I am in each component (4 rendering at same time) calling via

protected override async Task OnInitializedAsync()
{
api = new Api()
await api.LazyVariable
}

However, I see the API called twice across the 4 components image

timcassell commented 6 months ago

You're instantiating a new Api object which has the AsyncLazy<DTO> as an instance field. Either the Api instance needs to be shared, or the AsyncLazy<DTO> instance needs to be shared if you don't want it to run more than once.

dartuso commented 6 months ago

Awesome thank you! That was my suspicion.