Thursday 2 January 2020

Corotuine

First Add coroutine dependcies

On Android, it's essential to avoid blocking the main thread. The main thread is a single thread that handles all updates to the UI. It's also the thread that calls all click handlers and other UI callbacks. As such, it has to run smoothly to guarantee a great user experience.
For your app to display to the user without any visible pauses, the main thread has to update the screen every 16ms or more often, which is about 60 frames per second. Many common tasks take longer than this, such as parsing large JSON datasets, writing data to a database, or fetching data from the network. Therefore, calling code like this from the main thread can cause the app to pause, stutter, or even freeze. And if you block the main thread for too long, the app may even crash and present an Application Not Responding dialog.


dependencies {
  ...
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x"
}
zrrrunblocking{}
GlobalScope{}
CorotunieScope().launch
withContext()
Important: Using suspend doesn't tell Kotlin to run a function on a background thread. It's normal for suspend functions to operate on the main thread. It's also common to launch coroutines on the main thread. You should always use withContext() inside a suspend function when you need main-safety, such as when reading from or writing to disk, performing network operations, or running CPU-intensive operations.

Starting new coroutines

It’s important to note that you can’t just call a suspend function from anywhere. The suspend and resume mechanism requires that you switch from normal functions to a coroutine.
There are two ways to start coroutines, and they have different uses:
  1. launch builder will start a new coroutine that is “fire and forget” — that means it won’t return the result to the caller.
  2. async builder will start a new coroutine, and it allows you to return a result with a suspend function called await.


No comments:

Post a Comment