HomeiOS Developmentios - Why is the next code not working on the principle...

ios – Why is the next code not working on the principle thread?


Once I mark a protocol with async capabilities with @MainActor and it is conformance doesn’t specify it is capabilities are async, it’s not executing on major thread. I do not know if it is a bug or not.

For instance, given the next protocol and implementation:

@MainActor
protocol MyMainActorProtocol {
    func doStuff() async
}

struct MyMainActorStruct: MyMainActorProtocol {
    nonisolated init() {}
    func doStuff()  {
        print(">>> (Thread.isMainThread)")
    }
}

Once I execute this code:

Activity {
    let dependency: MyMainActorProtocol = MyMainActorStruct()
    print(">>> (Thread.isMainThread)")
    await dependency.doStuff()
}

each print statements run in a background thread.

However with the next changes of both

@MainActor
protocol MyMainActorProtocol {
    func doStuff()
}

struct MyMainActorStruct: MyMainActorProtocol {
    nonisolated init() {}
    func doStuff()  {
        print(">>> (Thread.isMainThread)")
    }
}

or

@MainActor
protocol MyMainActorProtocol {
    func doStuff() async
}

struct MyMainActorStruct: MyMainActorProtocol {
    nonisolated init() {}
    func doStuff() async  {
        print(">>> (Thread.isMainThread)")
    }
}

I get the proper end result, the place the physique of the perform contained in the struct runs in the principle thread.

Is that this anticipated conduct? What’s the rationalization behind it.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments