Last active
February 24, 2024 08:12
-
-
Save ANSCoder/7e06f0fde9275ff9cff5ecbd150c96ce to your computer and use it in GitHub Desktop.
MainActor for ViewModel class
This file contains 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
@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