What would be a good way to react to an mvi-style ...
# compose
p
What would be a good way to react to an mvi-style events flow within a composable? The IDE tells me I need to use a launched effect but I don't understand why and what I should use as a key.
you have two ways, either use on of those methods, or a LaunchedEffect. A launched effect allows you to control the lifecycle of the collect through the new api : https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda But it's probably overkill and you just want
collectAsState
here
p
Hm, that makes no sense to me. It's no state I'm reacting to
s
In this case you'll just use your view model as the key. If it was something like viewModel.getEvents(id), then you'll use the view model and id as the key
๐Ÿ‘ 1
n
yeah sorry, I forgot about the event part. LaunchedEffect allows you to start a coroutine, bound to a key. If the key change, it will restart the coroutine (the whole LaunchedEffect block) You can use LaunchedEffect(true) to use the same for the whole life of your composable
d
Composables are UI, they do not have state. Events alter UI State. So its not the job of your Composable to react to those events. CloseScreen and ToRecipe seems like they are navigation events. and should be handle by the part of your app managing navigation
โ˜๐Ÿผ 1
๐Ÿ‘๐Ÿผ 1
๐Ÿ‘ 2
โ˜๏ธ 2
p
My viewModel is final, I'll go with a (true). Thx ๐Ÿ™‚
n
this is the part that is kinda hard to get (at least I felt exactly the same at first) so you probably want to tinker a bit with everything to check how everyone works together ๐Ÿ˜„
d
I would advice against using LaunchEffect for this, you are going against the system in trying to use it like you wrote old UI in the View system
a
If you're looking to have Compose manage the presence or absence of an actor in your composition, the general pattern is:
Copy code
LaunchedEffect(dataSource) {
  dataSource.collect { event ->
    doSomethingWith(event)
  }
}
your instinct to not treat a stream of events as state using
collectAsState()
is spot on ๐Ÿ‘