Video wird geladen...

Video konnte nicht geladen werden

Zur Startseite

People often ask: “How should I perform async work from a synchronous context?”, like in a SwiftUI button closure. In such cases, it seems you have no choice but to spin up an unstructured “Task{…}”, but where should it go? 🤔 Watch for the answer:

12,324 Aufrufe • vor 2 Jahren •via X (Twitter)

7 Kommentare

Profilbild von Petr Šíma
Petr Šímavor 2 Jahren

Ok Ive been doing the opposite and thought I had a good reason too. The view doesn't decide what happens when the button is tapped, its the model's decision. So why should the fact that it'll do something async leak into the view? And what if the model needs to cancel the Task?

Profilbild von Point-Free
Point-Freevor 2 Jahren

The decision to go unstructured can come with some pretty big costs (losing top-down readability and cancellation propagation are two), and the language generally discourages spinning off tasks unless necessary. We do not feel it is necessary to do so earlier than the view most of the time, and avoiding so in the model means the model keeps all the benefits of staying structured. Now you may have designed your model in such a way that methods directly map to view actions (our preference, as well!), but a complex model may introduce shared helpers that need to be async, which leads to a mishmash of private async methods and public Task-returning sync methods that are more difficult to iterate on and maintain. We also think that it is easier to test models when you can just “await model.endpoint()” from an async test case.

Profilbild von Rhys Morgan
Rhys Morganvor 2 Jahren

This is exactly the question I had on the Slack! Thanks for highlighting it again 😁

Profilbild von Stephen Tolton
Stephen Toltonvor 2 Jahren

Is this from a published episode? This also matches what I generally do. I wonder if I got the idea from you guys?

Profilbild von Mirza Učanbarlić
Mirza Učanbarlićvor 2 Jahren

Why not call it ViewModel? It looks like one to me.

Profilbild von Rus
Rusvor 2 Jahren

How do you deal with non-Sendable warnings here when the model is a reference type?

Profilbild von Point-Free
Point-Freevor 2 Jahren

Typically the model has to be @MainActor.

Ähnliche Videos