Wait before all Cmds return before rendering the next view

When Elm processes the update function it return the updated Model and a list of Cmds to execute. AFAIK, these Cmds run asynchronously, meaning the updated Model is sent to the view function to be rendered while the Cmds are still executing. Then, when these Cmds return, the Model is updated once again for each message received from the Cmds and the view is updated.

I’m thinking if it is possible to somehow wait for all the Cmds to return, before rendering the next view? A possible use case for this would be to send an HTTP request to the server, and wait for it return either a 200 OK or a 404 Not Found, and this would be used to decide which view would be presented (successful presentation of the resource or a generic Not Found page).

Another possible use case would be to prevent “loading” screens or spinners across the view and just show complete views.

Thanks!

Not updating the view would mean that the whole app freezes until you get the reply. I don’t think you want this. But, you can certainly make it so that you have a custom datatype that collects all the replies and only when all replies have come back do you change what is displayed in your view.

1 Like

Yes, that’s exactly what I was thinking would happen. This could be mitigated with an intermediate “Loading” bar on top of the current view, but I understand it kind of defeats the purpose.

Take a look at the remote-data package, I think this will do exactly what you’re looking for. This is really commonly used. It’s very simple but powerful. You can even take several http requests and merge it into a single data type, see its mapN functions. Using the mapN functions you, you can show a loading spinner if any of the requests are loading, or an error message if any of the requests have an error. Pretty handy!

2 Likes

Be aware that an Elm application does not necessarily proceed like this: update -> view -> update -> view -> update -> view -> ..., that is, 1 update and 1 view interleaved. As the Cmds are asynchronous and the view function is only called on the animation frame, there can be many updates per view. This asynchronousity is necessary to deal with the user interaction and other system (HTTP requests, timer, keyboard, mouse etc) - and for that reason you would not want to block on either the update or the view functions.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.