Skip to content

Instantly share code, notes, and snippets.

@ANSCoder
Last active February 24, 2024 08:12
Show Gist options
  • Save ANSCoder/855e252fd5c64ba27396391ccaff526f to your computer and use it in GitHub Desktop.
Save ANSCoder/855e252fd5c64ba27396391ccaff526f to your computer and use it in GitHub Desktop.
MainActor in SwiftUI
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