小编Zag*_*ahr的帖子

在调用声明为 @MainActor 的异步函数的任务中使用 @MainActor

我想了解是否需要考虑以下代码块将任务本身声明为 MainActor。

func login() {
    Task { [weak self] in
        let result = await self?.loginService.start()

        if result == .successful {
            self?.showWelcomeMessage() // updating the UI here
        }
    }
}

final class LoginService {

    @MainActor
    func start() async -> LoginResult {
        // Doing some UI related operations here
    }
}

Run Code Online (Sandbox Code Playgroud)

当任务内部调用的异步函数已经声明为 MainActor 时,我是否还需要将任务本身声明为 MainActor ?像这样:

func login() {
    Task { @MainActor [weak self] in
        let result = await self?.loginService.start()

        if result == .successful {
            self?.showWelcomeMessage() // updating the UI here
        } …
Run Code Online (Sandbox Code Playgroud)

ios async-await swift mainactor swift-concurrency

5
推荐指数
1
解决办法
1886
查看次数

标签 统计

async-await ×1

ios ×1

mainactor ×1

swift ×1

swift-concurrency ×1