如何立即开始执行Kotlin Coroutine [英] How to start executing of Kotlin Coroutine immediately

查看:79
本文介绍了如何立即开始执行Kotlin Coroutine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想立即开始协程.我有一段代码:

I want to start a coroutine immediately. I have a piece of code:

class SampleActivity : AppCompatActivity(), CoroutineScope {

    private var job: Job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Log.d("SampleActivity", "Before launch")

        launch {
            Log.d("SampleActivity", "Inside coroutine")
        }

        Log.d("SampleActivity", "After launch")
    }
}

输出为:

Before launch
After launch
Inside coroutine

是否可以按以下顺序实现输出?

Is it possible to achieve the output in the following order?

Before launch
Inside coroutine
After launch

推荐答案

尝试通过以下方式启动它:

Try to launch it with:

启动(Dispatchers.Main.immediate)

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆