Created
March 29, 2025 18:17
-
-
Save hmlongco/57181651ecd6a8415d3af3d07182ee21 to your computer and use it in GitHub Desktop.
ViewModel called from task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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