Browse Questions
- Both run code when a view appears, but task {} is purpose-built for async work.
- These are three distinct levels of organisation in an Xcode workspace.
- AsyncStream converts callback or delegate-based event sources into an AsyncSequence you can iterate over with for await.
- Every UIView has a CALayer that does the actual drawing and compositing.
Answer:
Both run code when a view appears, but task {} is purpose-built for async work.
onAppear | task | |
|---|---|---|
| Async support | ❌ No | ✅ Yes |
| Auto-cancels | ❌ No | ✅ Yes (when view disappears) |
| Retry on id change | ❌ No | ✅ With id: parameter |
Code Example:
struct ArticleView: View {
@State private var article: Article?
var body: some View {
Text(article?.title ?? "Loading...")
.task {
// automatically cancelled if view disappears
article = await ArticleService.fetch()
}
}
}