Last active
February 24, 2024 08:12
-
-
Save ANSCoder/855e252fd5c64ba27396391ccaff526f to your computer and use it in GitHub Desktop.
MainActor in SwiftUI
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 UserViewModel: ObservableObject { | |
@Published private(set) var userDetails = UserDetails() | |
func loadUserDetails() { | |
Task { | |
do { | |
userDetails = try await fetchUserData() | |
} catch { | |
showError(error) | |
} | |
} | |
} | |
@MainActor | |
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