Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Local vs Global Actors in Observable Model Objects

I have the following SwiftUI Observable model class along with a local & global actor variables that fails to build with the error Global actor 'MyGlobalActor'-isolated default value in a nonisolated context. My question is what is special about global actor that build fails but build succeeds for local actor? Does the init method in local actor runs on default context but the global actor runs in isolated context?

import SwiftUI
    
@Observable
final class Model {
    let testActor = TestLocalActor() //This builds 
    let testGlobalActor = TestGlobalActor() //Build fails here
}

actor TestLocalActor {
    init() {
        
    }
}

@MyGlobalActor
final class TestGlobalActor {
    init() {
        
    }
}

@globalActor
actor MyGlobalActor: GlobalActor {
   static let shared = MyGlobalActor()
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does the init method in local actor runs on default context but the global actor runs in isolated context?

Correct. More accurately, non-async initialisers of actors are considered non-isolated (see also), whereas once you isolate the whole class to a global actor, the class’ init is also isolated to the global actor.

You can add the nonisolated modifier to the init, if you want to exclude it from the global actor’s isolation.

@MyGlobalActor
final class TestGlobalActor {
    nonisolated init() {
        
    }
}

@Observable
final class Model {
    let testGlobalActor = TestGlobalActor() // now this compiles
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading