Home > Net >  Alternative ways to receive result from async/await on Main Thread for Swift
Alternative ways to receive result from async/await on Main Thread for Swift

Time:12-01

Recently, I ran into a problem where I got a warning for updating UI on background task.

func didInit() async {
    listOfTodo = await interactor.getTodos()
}

I tried to wrap the function body inside DispatchQue.main.async {}, but I got an error.

I then found a solution which I have to put @MainActor on top of my function, but I feel like there are other solutions that would make more sense, or this is the only way to work with async/await on Main Thread?

@MainActor
func didInit() async {
    listOfTodo = await interactor.getTodos()
}

CodePudding user response:

You're approaching this backwards. If interactor.getTodos() must be run on the main actor, then it should be marked @MainActor, not the caller. But if didInit is logically "a UI-updating method," then it's fine to mark it @MainActor as well.

Or you can use MainActor.run {...} to manually move this one call to the main actor. It all comes down to what you mean to express.

CodePudding user response:

I then found a solution which I have to put @MainActor on top of my function

Well done.

but I feel like there are other solutions that would make more sense

Why do you "feel" that way, and how does this "feeling" relate to programming? What would these other solutions look like?

or this is the only way to work with async/await on Main Thread?

async/await is not really about threads. But it is useful to distinguish the main thread from not the main thread. The way you guarantee which of those your code runs on is with an actor. That is precisely what you have done. Given the minimalism of the code you've shown, that's really all there is to say. In the limited context of the question, what you've done is exactly right.

  • Related