Best Practice for Cancelling DataStore Flow When Component Is Destroyed Using Decompose 🛠️✨ #840
-
Hi Arkivanov, 👋 I'm using the Decompose library and implementing a HomeListComponent where I need to cancel a DataStore flow when the component is destroyed or cleared. I noticed the onCleared function in ViewModels seems analogous to doOnDestroy in Decompose. I’ve implemented something similar to how this would be handled with ViewModel, but using Decompose instead. The reason for this approach is that flows should ideally not be collected in ViewModels, and if they are, their jobs must be controlled and canceled when they are no longer needed to avoid memory leaks or unexpected behavior. Before I proceed, I wanted to confirm if this looks like a good approach or if there’s a better way to handle flow cancellation in such a scenario with Decompose. Here's the relevant code snippet:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
As mentioned in the docs, if you are using Also, most likely you want to use |
Beta Was this translation helpful? Give feedback.
As mentioned in the docs, if you are using
coroutineScope(...)
extension function, the scope is cancelled automatically when the component is destroyed. So there should be no need to manually cancel the jobs.Also, most likely you want to use
Dispatchers.Main.immediate
instead ofDispatchers.IO
. DataStore should switch the threads on its own anyway, and you should have less problems with threading when updating states etc. In particular,_state.value = _state.value.copy(currentCity = location)
is not atomic, you may have problems when that code is called concurrently.