xani
xani

Reputation: 804

Async not waiting for await

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.

Upvotes: 1

Views: 1043

Answers (1)

Roman  Elizarov
Roman Elizarov

Reputation: 28628

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()
}

Upvotes: 4

Related Questions