Async not waiting for await

痴心易碎 提交于 2019-12-12 05:48:36

问题


I'm new to Kotlin and the coroutines. However I want to use it to initialize the Android ThreeTen backport library which is a long running task. I'm using the Metalab Async/Await Library (co.metalab.asyncawait:asyncawait:1.0.0).

This is my code:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val application = this

    async {

        //non-blocking initialize ThreeTen
        await { AndroidThreeTen.init(application) }

        //initialize UI on UI thread which uses the ThreeTen library
        initUI()

    }
}

Now I have the problem that the library is not initialized when initializing the UI. From my understanding initUI shouldn't be called before AndroidThreeTen.init is called.


回答1:


The short answer is that you should not use Kotlin coroutines for that.

The long answer is that your code needs AndroidThreeTen to be initialised before you initialise your UI, so you have to wait for AndroidThreeTen.init to finish before trying to invoke initUI anyway. Because of that inherent need to wait, there is little reason to overcomplicate your code. Coroutines are not magic. They will not make waiting for something that takes a lot of time somehow faster. AndroidThreeTen.init will take the same amount of time with coroutines or without them.

You should just write your code like this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val application = this

    AndroidThreeTen.init(application)
    initUI()
}


来源:https://stackoverflow.com/questions/43898785/async-not-waiting-for-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!