A practical SwiftUI demonstration app that showcases the differences between .task() and .onAppear() view modifiers through a live cat facts streaming example.
This project accompanies the article "Understanding When to Use .task() vs .onAppear in SwiftUI" published on Clement's Substack.
- Live Cat Facts Stream: Demonstrates
.task()modifier with continuous data streaming - Automatic Task Management: Shows automatic cancellation when view disappears
- AsyncStream Implementation: Real-world example of async/await in SwiftUI
- Clean Architecture: Simple, educational code structure
- Performs synchronous actions when a view appears
- One-time setup operations
- Cannot handle async/await directly
- Handles asynchronous operations seamlessly
- Task lifetime tied to view lifecycle
- Automatic cancellation when view disappears
- Support for task priorities
- Built-in memory management
The app demonstrates a practical use case where:
- Home View: Simple navigation starting point
- Live Facts View: Streams cat facts every 2 seconds using
.task() - Automatic Cleanup: When navigating away, the async task automatically cancels
.task {
for await newFact in catFactStream() {
withAnimation {
fact = newFact
}
}
}- Clone this repository
- Open
onAppear.xcodeprojin Xcode - Build and run on iOS Simulator or device
- Navigate to "Show Live Cat Facts" to see
.task()in action
- Use
.onAppear()for simple, synchronous setup tasks - Use
.task()for async operations, network requests, and long-running processes .task()provides better resource management and automatic cleanup- Task priorities help optimize performance in complex apps
Read the full article: Understanding When to Use .task() vs .onAppear in SwiftUI
- iOS 15.0+
- Xcode 13.0+
- Swift 5.5+
This project demonstrates modern SwiftUI patterns and Swift concurrency features for educational purposes.
