https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

Vivek Sharma

01/27/2021, 2:49 PM
I am reading basics of coroutines from docs, I have a doubt like :
Copy code
launch {
   doingNetworkCall()  // this is suspend function
}
// doing some work on main thread here like loading
so assume doingNetworkCall() is taking some time, till that time that function get suspended OR it just works in background thread and on completion it returns like callback and do other work and if this work is getting suspended, then when it is getting resumed to achieve desired output
c

Casey Brooks

01/27/2021, 3:01 PM
You will want to run everything in the same coroutine (one
launch { }
block) and switch contexts as necessary to ensure things get run on the proper threads.
Copy code
launch { 
    withContext(Dispatchers.Main) {
        showProgressBar()
    }
    val resultFromApiCall = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { 
        doingNetworkCall()
    }
    withContext(Dispatchers.Main) { 
        dismissProgressBar()
        updateUiWithInfoFromApi(resultFromApiCall)
    }
}
v

Vivek Sharma

01/27/2021, 3:06 PM
oh okay thanks
l

louiscad

01/27/2021, 3:35 PM
Note that this would probably crash your app when there's no internet, unless you catch the possible exceptions (but not
CancellationException
)
v

Vivek Sharma

01/27/2021, 4:48 PM
yeah okay, I am taking just an example
4 Views