1

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
xani
  • 784
  • 1
  • 7
  • 21
  • You should load the UI first then data second (or sooner in the background): http://stackoverflow.com/a/43151714/882912 Otherwise you freeze up your UI while you load the data. That way you can show a progress bar. – KTCO May 13 '17 at 00:08

1 Answers1

4

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()
}
Roman Elizarov
  • 27,053
  • 12
  • 64
  • 60
  • 1
    Thanks for your answer. On the one hand you are right, it adds nothing to the performance. On the other hand I still don't understand why my code doesn't work. Is it [like here in c#](https://stackoverflow.com/questions/36115580/async-await-not-waiting?rq=1) because of void which is bad practice? – xani May 11 '17 at 08:56
  • That would be a question that authors of Metalab Async/Await Library might be able to answer. If you were using `kotlinx.coroutines`, then you could write it like that and it would work https://gist.github.com/elizarov/0b3e3386d304478368b3eb0380b6f25a – Roman Elizarov May 12 '17 at 10:00