Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Why can you run a Kotlin coroutine on the main thread?

I am having trouble understanding why this piece of code can work properly:

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

    launch(Dispatchers.Main) {
        log("A")
    }

    log("B")
}

which is supposed to output B first, and then A.

Does this work, because the main thread is already controlled by coroutines? Or does the coroutines API somehow magically inject code into the main thread?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Sometimes you need data from an async source. Also you can't proceed without that data like getting logged in user info from Room Database or from online server, In this case you usually block main thread so that you get required data and then proceed further.

over 4 years ago · Santiago Trujillo Report

0

The UI/main thread in Android (and other UI frameworks as well) runs a so called event loop. That means it waits for tasks to be scheduled to it, it has a queue of such tasks and executes them sequentially. For example, when you click on a button, internally onClick action is scheduled to be run on the main thread. But the user is also allowed to schedule their tasks manually, for example by using runOnUiThread() or getMainLooper().

Dispatchers.Main is just yet another way to schedule something on the main thread. It doesn't mean coroutines take full control over the main thread or that they somehow, magically inject anything to it. Main thread is cooperative, it allows scheduling of tasks and coroutines just use this feature.

Also, you asked in the comments, how is it possible that both log statements are run in parallel, but on the same thread. They are not run in parallel. onCreate() only schedules log("A") to be executed later, this is added to the queue. Then log("B") is invoked and only when onCreate() finishes, the main thread can start executing log("A") block. So this is actually sequential, but not in the top-to-bottom order.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!