coroutine
1. Three schedulers to specify where coroutines should run.
- Dispatchers.Main - Use this dispatcher to run coroutines on the Android main thread. This scheduler should only be used to interact with the interface and perform quick work. Examples include calling
suspend
functions, running Android interface framework operations, and updating LiveData objects. - Dispatchers.IO - This dispatcher is specifically optimized for performing disk or network I/O outside of the main thread. Examples include using Room components , reading data from or writing data to files, and performing any network operations.
- Dispatcher.Default - This dispatcher is optimized for performing CPU-intensive work outside of the main thread. Examples of use cases include sorting lists and parsing JSON.
2. Don't hardcode Dispatchers.
//推荐做法
class NewsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
suspend fun loadNews() = withContext(defaultDispatcher) { /* ... */ }
}
//错误用法
class NewsRepository {
// DO NOT use Dispatchers.Default directly, inject it instead
suspend fun loadNews() = withContext(Dispatchers.Default) { /* ... */ }
}