Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I wait till the coroutine scope execution finishes in my Android App?

I want to clarify one doubt regarding Kotlin Coroutines.

How can I delay the execution of the next line or next block of code in my app until the response of my ongoing API comes?

For e.g. Suppose I want to call one API when a user opens the app and only after I get the response from that API I want to draw the views or anything else. It can be as simple as log anything or show toast or something like that.

Note: Without using runBlocking{ } or delay() methods.

like image 373
DharmeshBasapati Avatar asked Oct 20 '25 19:10

DharmeshBasapati


1 Answers

For a simple tasks you could use invokeOnCompletion which will execute only after the coroutine finish it's job.

Here's a little example

lifecycleScope.launch(Dispatchers.IO) {
        //heavy calculations
    }.invokeOnCompletion { 
        Toast.makeText(requireContext(), "Coroutine ended it's job", Toast.LENGTH_SHORT).show()
    }
like image 174
qki Avatar answered Oct 23 '25 11:10

qki