Загрузка видео...

Не удалось загрузить видео

На главную

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 просмотров • 2 лет назад •via X (Twitter)

Комментарии: 7

Фото профиля Petr Šíma
Petr Šíma2 лет назад

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
Point-Free2 лет назад

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
Rhys Morgan2 лет назад

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

Фото профиля Stephen Tolton
Stephen Tolton2 лет назад

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ć
Mirza Učanbarlić2 лет назад

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

Фото профиля Rus
Rus2 лет назад

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

Фото профиля Point-Free
Point-Free2 лет назад

Typically the model has to be @MainActor.

Похожие видео