Sergio
Sergio

Reputation: 30745

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

Upvotes: 4

Views: 11838

Answers (1)

Demigod
Demigod

Reputation: 5635

Try to launch it with:

launch(Dispatchers.Main.immediate)

More info in this article.

Upvotes: 3

Related Questions