Is it possible to update Kotlin StateFlow without emitting the change? The use case is that when user zooms a chart view, I would like to have that restored when activity resumes but skip the StateFlow events while zooming is in progress.
Asked
Active
Viewed 1,877 times
2 Answers
1
Yes. Although it may lead to obscure bugs.
On a StateFlow<T>
you can get the latest known value (bear in mind that it might not exist). Since Kotlin (like java) uses references for objects (it might not work for primitive types) then you may apply modifications to returned object from yourState.value
.

Some random IT boy
- 7,569
- 2
- 21
- 47
-
A StateFlow always has a value., so it's incorrect to say it might not exist. – Tenfour04 Jan 12 '22 at 02:08
-
True. I got confused with `MutableStateFlow` – Some random IT boy Jan 12 '22 at 08:15
-
MutableStateFlow, being a subtype of StateFlow, always has a value as well. You might be thinking of LiveData on Android. – Tenfour04 Jan 12 '22 at 14:16
-
That, precisely – Some random IT boy Jan 12 '22 at 14:23
0
If you want to restore the latest state only when your Activity resumes, then don't collect
the flow. You can get the latest value from the StateFlow.value
property in Activity.onResume()
. But then again, then you don't need a Flow in the first place and can simply use a property that directly stores the value you want.

Tenfour04
- 83,111
- 11
- 94
- 154
-
This does not work well because when an activty is resumed the data gets loaded into the chart `asyncronously` and `onResume` may get called prior to data is loaded causing to zoom action make no effect. – yaugenka Jan 12 '22 at 09:37
-