Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created March 29, 2025 18:17
Show Gist options
  • Save hmlongco/57181651ecd6a8415d3af3d07182ee21 to your computer and use it in GitHub Desktop.
Save hmlongco/57181651ecd6a8415d3af3d07182ee21 to your computer and use it in GitHub Desktop.
ViewModel called from task
class MyViewModel: ObservableObject {
@Published var items: [Item] = []
@MainActor
func loadData() async {
items = await fetchData()
}
}
struct MyView: View {
@StateObject private var viewModel = MyViewModel()
var body: some View {
List(viewModel.items) { item in
Text(item.name)
}
.task {
await viewModel.loadData()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment