【问题标题】:Kotlin Coroutines - Are nested coroutines the proper way to handle different threading within one coroutine?Kotlin Coroutines - 嵌套协程是在一个协程中处理不同线程的正确方法吗?
【发布时间】:2018-05-03 23:43:50
【问题描述】:

我第一次在基本的网络调用上尝试使用协程而不是 RxJava,看看它是什么样的,并遇到了一些延迟/线程问题

在下面的代码中,我正在执行网络调用userRepo.Login(),如果发生异常,我会显示错误消息并停止我在函数开始时启动的进度动画。

如果我将所有内容都留在 CommonPool 上(或不添加任何池),它会崩溃,说如果发生异常,动画必须在 Looper 线程上完成。在其他情况下,我收到错误说这也必须在 UI 线程上完成,同样的问题,不同的线程要求。

但我不能在 UI 线程上启动整个协程,因为登录调用会阻塞,因为它在 UI 线程上并且会打乱我的动画(这是有道理的)。

我认为解决此问题的唯一方法是在现有协程内的 UI 线程上启动一个新协程,这可行,但看起来很奇怪。

这是正确的做事方式,还是我错过了什么?

override fun loginButtonPressed(email: String, password: String) {

    view.showSignInProgressAnimation()

    launch(CommonPool) {
        try { 
            val user = userRepo.login(email, password)

            if (user != null) {
                view.launchMainActivity()
            }

        } catch (exception: AuthException) {
            launch(UI) {
                view.showErrorMessage(exception.message, exception.code)
                view.stopSignInProgressAnimation()
            }
        }
    }
}

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    您应该从相反的一端开始:启动一个基于 UI 的协程,然后将繁重的操作交给外部池。选择的工具是withContext()

    override fun loginButtonPressed(email: String, password: String) {
        view.showSignInProgressAnimation()
        // assuming `this` is a CoroutineScope with dispatcher = Main...
        this.launch {
            try {
                val user = withContext(IO) { 
                    userRepo.login(email, password) 
                }
                if (user != null) {
                    view.launchMainActivity()
                }
            } catch (exception: AuthException) {
                view.showErrorMessage(exception.message, exception.code)
                view.stopSignInProgressAnimation()
            }
        }
    }
    

    这样您就可以保留您的自然 Android 编程模型,该模型假定 GUI 线程。

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 2020-07-28
      • 1970-01-01
      • 2019-04-13
      • 2018-04-02
      • 2020-07-19
      • 1970-01-01
      • 2022-01-18
      • 2019-12-26
      相关资源
      最近更新 更多