4

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.

yaugenka
  • 2,602
  • 2
  • 22
  • 41

2 Answers2

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
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
  • Then check the value when the data arrives. – Tenfour04 Jan 12 '22 at 14:18