![]() ![]() But the code you've provided ends up doing something as follows: Handler(Looper.getMainLooper()).post( It doesn't "magically inject itself into the Main thread". Same story in case we compiled for embedded devices like Arduino or ESP32's.įor Android coroutines implementation it uses the Executors, Handlers and Looper API's. Regardless of the target the concept remains the same: Kotlin coroutines.įor example: in the JavaScript world we don't have threads: we just have the synchronous and asynchronous task stacks. Kotlin is just a programming language that later compiles to different other languages (JVM bytecode for Java and Android, LLVM for native targets and JS for Browser or NodeJS targets). (Although behind the scenes you'll see that indeed you're calling that code from the main thread). And you're not sending your task to "the main thread" but to the Main coroutine Dispatcher. ![]() So this is actually sequential, but not in the top-to-bottom order.Ĭoroutines is a Kotlin concept. Then log("B") is invoked and only when onCreate() finishes, the main thread can start executing log("A") block. ![]() onCreate() only schedules log("A") to be executed later, this is added to the queue. Main thread is cooperative, it allows scheduling of tasks and coroutines just use this feature.Īlso, you asked in the comments, how is it possible that both log statements are run in parallel, but on the same thread. It doesn't mean coroutines take full control over the main thread or that they somehow, magically inject anything to it. But the user is also allowed to schedule their tasks manually, for example by using runOnUiThread() or getMainLooper().ĭispatchers.Main is just yet another way to schedule something on the main thread. For example, when you click on a button, internally onClick action is scheduled to be run on the main thread. That means it waits for tasks to be scheduled to it, it has a queue of such tasks and executes them sequentially. The UI/main thread in Android (and other UI frameworks as well) runs a so called event loop. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |