Can someone offer some direction? I have a VM that...
# compose
j
Can someone offer some direction? I have a VM that creates a stateholder object containing mutable states, and now im trying to add event tracking when the user sets a certain mutable state value to specific value, is there a good way for me to observe this and trigger my tracking function from the vm? or should i pass the tracker to the composable within the state and trigger it this way instead? or maybe something else...
s
Are you using a
Flow
to represent the stream of state? If so, you can launch a tracking coroutine pretty easily.
j
im not, maybe i should have been doing this.
its just a object with a bunch of mutable states within it.
s
Copy code
private val state = MutableStateFlow(initialState)
init {
  viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
    state.filter { ... }
      .onEach { ... }
  }
}
When you emit a new state to
state
, that coroutine will reactively perform your side effect
j
yeah... im wondering now if i should migrate that direction or pass my tracker into that state and let my view trigger it, but that seems like a hackkkkk
s
if you're relying on your Compose layout to trigger events, you would need to be careful to not retrigger on recomposition
it's a pain and not really recommended
1
w
If you're doing it on set though, that is guaranteed to be only called once. Like,
onClick
is never invoked twice for an event regardless of how many recompositions happen.
💯 1
I think where you track it depends on what the event is for. If you're tracking button click, then I'd probably put it in Compose. If it's strictly state change, from anywhere, then VM makes sense. Ideally just avoid the case where you start tracking where a state update came from. That gets very messy.