swiftdependency-injectionswiftuiasync-awaitresolver

Using Resolver to Register a View Model with "@Main Actor" Annotation


My view model has multiple functions that use Task in order to execute use cases. I use the "@Main Actor" annotation for publishing UI updates on the main thread. I get an error when trying to register the view model in Resolver.

Is there a way to register these type of view models in Resolver?

Error

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

Registering

extension Resolver: ResolverRegistering {
    public static func registerAllServices() {
        register {
            MeetingListViewModel() as MeetingListViewModel
        }
        .scope(.graph)
    }
}

ViewModel

@MainActor
class MeetingListViewModel: ObservableObject {
   ...
}

View

struct MeetingListView: View {
    @StateObject var viewModel: MeetingListViewModel = Resolver.resolve()
    ...
}

Solution

  • I figured out we could simply add @MainActor to the Resolver extensions like so:

    @MainActor
    public static func registerWhatever() {
        ...
    }
    

    Same thing for the main function

    @MainActor
    public static func registerAllServices() {
        ...
    }
    

    It seems to work completely fine for me