architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[Question] coroutine question in TasksViewModel

Open tak1111 opened this issue 5 years ago • 1 comments

Line 201 in the TasksViewModel,

viewModelScope.launch { result.value = filterItems(tasksResult.data, getSavedFilterType()) }

Why google use coroutine??? what are the advantages or reasons??

tak1111 avatar Jun 06 '20 15:06 tak1111

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.

VaradGupta23 avatar Jul 21 '25 06:07 VaradGupta23