Video yükleniyor...
Video Yüklenemedi
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 görüntüleme • 2 yıl önce •via X (Twitter)
7 Yorum

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?

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.

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

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

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

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

Typically the model has to be @MainActor.
