Video yükleniyor...

Video Yüklenemedi

Ana Sayfaya Dön

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

Petr Šíma profil fotoğrafı
Petr Šíma2 yıl önce

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?

Point-Free profil fotoğrafı
Point-Free2 yıl önce

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.

Rhys Morgan profil fotoğrafı
Rhys Morgan2 yıl önce

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

Stephen Tolton profil fotoğrafı
Stephen Tolton2 yıl önce

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

Mirza Učanbarlić profil fotoğrafı
Mirza Učanbarlić2 yıl önce

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

Rus profil fotoğrafı
Rus2 yıl önce

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

Point-Free profil fotoğrafı
Point-Free2 yıl önce

Typically the model has to be @MainActor.

Benzer Videolar