Search code examples
androidkotlinkotlin-coroutinescoroutinecoroutinescope

How to start executing of Kotlin Coroutine immediately


I want to start a coroutine immediately. I have a piece of code:

class SampleActivity : AppCompatActivity(), CoroutineScope {

    private var job: Job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        Log.d("SampleActivity", "Before launch")

        launch {
            Log.d("SampleActivity", "Inside coroutine")
        }

        Log.d("SampleActivity", "After launch")
    }
}

The Output is:

Before launch
After launch
Inside coroutine

Is it possible to achieve the output in the following order?

Before launch
Inside coroutine
After launch

Solution

  • Try to launch it with:

    launch(Dispatchers.Main.immediate)

    More info in this article.