正在加载视频...

视频加载失败

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.

相关视频