Use the .task modifier to run async work when a view appears — perfect for loading data.
class FeedModel: ObservableObject {
@Published var posts: [Post] = []
func load() async {
let url = URL(string: "https://api.example.com/posts")!
if let (data, _) = try? await URLSession.shared.data(from: url) {
posts = (try? JSONDecoder().decode([Post].self, from: data)) ?? []
}
}
}
struct FeedView: View {
@StateObject private var model = FeedModel()
var body: some View {
List(model.posts) { Text($0.title) }
.task { await model.load() } // runs on appear
}
}
Tip:
.task auto-cancels the work if the view disappears — no manual cleanup needed.Summary
Load data with async/await inside a view model and trigger it from .task; @Published updates the UI automatically.