Search code examples
android-fragmentskotlinx.coroutines

kotlin coroutines with android client side interaction


Lets say I have one fragment that opens another fragment and waits for answer from that fragment.

Is it possible with kotlin coroutines to make the code look synchronous?

meaning something like this?

result = await openFragment()

Solution

  • With kotlin 1.3 coroutine you can do this:

    val myFragment = async { //Your asynchronous task here }
    

    This will return a Deferred object, as the official documentation describes, "a light-weight non-blocking future that represents a promise to provide a result later". When you want to get the result of this task, do this:

    val result = myFragment.await()
    

    Or, you can make use of Async-style functions to initiate your task outside a coroutine. Just define a function like this:

    fun openFragment() = GlobalScope.async {
        //Your asynchronous task here
    }
    

    Then you can do this outside a coroutine:

    val myFragment = openFragment()
    

    Then you can get the result of the task the same way as above through the await function. This line still has to be put inside a coroutine.

    val result = myFragment.await()