Skip to content

Instantly share code, notes, and snippets.

@ANSCoder
Last active February 24, 2024 08:12
Show Gist options
  • Save ANSCoder/7e06f0fde9275ff9cff5ecbd150c96ce to your computer and use it in GitHub Desktop.
Save ANSCoder/7e06f0fde9275ff9cff5ecbd150c96ce to your computer and use it in GitHub Desktop.
MainActor for ViewModel class
@MainActor
class UserViewModel: ObservableObject {
@Published private(set) var userDetails = UserDetails()
func loadUserDetails() {
Task {
do {
userDetails = try await fetchUserData()
} catch {
showError(error)
}
}
}
func fetchUserData() async throws -> UserDetails {
try await withCheckedThrowingContinuation { continuation in
fetchUserData { result in
switch result {
case .success(let user):
continuation.resume(returning: user)
case .failure(let error):
continuation.resume(throwing: error)
}
}
}
}
func showError(_ error: Error) {
// handle errors
}
func fetchUserData(_ result: @escaping(Result<UserDetails, Error>)-> ()) {
// your async operation ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment