Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MainActor issue with ObservableObject's #135

Closed
cabyambo opened this issue Jul 7, 2023 · 1 comment
Closed

MainActor issue with ObservableObject's #135

cabyambo opened this issue Jul 7, 2023 · 1 comment

Comments

@cabyambo
Copy link

cabyambo commented Jul 7, 2023

I am getting an error when trying to register an ObservableObject marked with @MainActor

Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context

Here's how I am registering the object:

extension Container {
    var homeViewModel: Factory<HomeViewModel> {
        self { HomeViewModel() }
    }
}

And here is the object itself:

import Foundation
import Factory
import Combine

@MainActor // Removing this fixes the error, but I need this
class HomeViewModel: ObservableObject {
    @Injected(\.cardImageUrlRepository) private var cardImageUrlRepository
   
    @Published private(set) var cardImageUrls: [String] = []
    
    init() {
        fetchCreditCardImageUrls()
    }
    
    private func fetchCreditCardImageUrls() {
        Task {
            // Fetch data using repository
            // Set cardImageUrls to fetched data
        }
    }
}

Is it possible to keep the @MainActor tag?

@hmlongco
Copy link
Owner

hmlongco commented Jul 7, 2023

If you mark the entire class that way then you need to mark the initializer as nonisolated in order to get around that particular problem. Marking the entire class with MainActor marks every function and method within the class as MainActor, including the initializer.

I tend to prefer marking async functions as MainActor as needed, and not the entire class. I wrote a lot about that on Medium: https://betterprogramming.pub/async-await-and-mainactor-strategies-cc35b6c58b52

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants