Best Practices For Kotlin Coroutine in Android
Best Practices For Kotlin Coroutine in Android
Android Developer
// Good Practice
class NewsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
){
withContext(defaultDispatcher) { /* ... */ }
suspend fun loadNews() = withContext(defaultDispatcher)
}
// Bad Practice
class NewsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
){
withContext(Dispatchers.Default) { /* ... */ }
suspend fun loadNews() = withContext(Dispatchers.Default)
}
ViewModel layer should create coroutines
The UI layer should be dumb; it should not be directly attached to any
business logic. Once the ViewModel gets destroyed, all the coroutines
within the ViewModel scope will be cleared, preventing crashes and
making unit testing easier.
// Good Practice
class LatestNewsViewModel (
private val getLatestNewsUsecase: GetLatestNewsUseCase
): ViewModel() {
fun loadNews() {
viewModelScope.launch
viewModelScope.launch{{ // Launch coroutine within viewModel scope
val latestNewsWithAuthors = getLatestNewsWithAuthors()
}
}
}
// Bad Practice
class LatestNewsViewModel (
private val getLatestNewsUsecase: GetLatestNewsUseCase
): ViewModel() {
// Good Practice
class NewsRepository(
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
){
// Good Practice
class LatestNewsViewModel : ViewModel() {
// Bad Practice
class LatestNewsViewModel : ViewModel() {
// Example
class ArticlesRepository(
private val articlesDataSource: ArticlesDataSource,
private val externalScope: CoroutineScope, // Application class scope
){
// As we want to complete bookmarking the article even if the user moves
// away from the screen, the work is done creating a new coroutine
// from an external scope
// Example
class ArticlesRepository(
private val articlesDataSource: ArticlesDataSource
){
// As we want to complete bookmarking the article even if the user moves away
// from the screen, the work is done creating a new coroutine with GlobalScope
// Bad Practice
class NewsRepository(private val defaultDispatcher = Dispatchers.Default) {
Use Job() - when you want if any single child coroutine fails, it
should also fail the parent coroutine.
async {...} throws the exception only when you call .await().
Was this helpful?
SAVE THIS POST!