[Question] coroutine question in TasksViewModel
Line 201 in the TasksViewModel,
viewModelScope.launch { result.value = filterItems(tasksResult.data, getSavedFilterType()) }
Why google use coroutine??? what are the advantages or reasons??
Great question! Let's break down why Google uses a coroutine in TasksViewModel — specifically:
viewModelScope.launch { result.value = filterItems(tasksResult.data, getSavedFilterType()) } Why use a coroutine here? Structured concurrency via viewModelScope
viewModelScope is tied to the lifecycle of the ViewModel. When the ViewModel is cleared, all running coroutines are automatically canceled — avoiding memory leaks or crashes from background work continuing after the screen is gone.
Asynchronous or suspendable logic
Even if filterItems() and getSavedFilterType() are currently not suspending, the coroutine block allows them to be easily replaced or extended with suspend functions (e.g. loading filter from DataStore or Room) without changing the surrounding code structure.
Non-blocking main thread
Even small data operations or future enhancements (like logging, analytics, I/O) can run without freezing the UI.