Paul Woitaschek

    Paul Woitaschek

    1 year ago
    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
    Paul Woitaschek

    Paul Woitaschek

    1 year ago
    Hm, that makes no sense to me. It's no state I'm reacting to
    s

    Se7eN

    1 year ago
    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
    n

    nitrog42

    1 year ago
    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
    Daniele Segato

    Daniele Segato

    1 year ago
    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
    Paul Woitaschek

    Paul Woitaschek

    1 year ago
    My viewModel is final, I'll go with a (true). Thx 🙂
    n

    nitrog42

    1 year ago
    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 😄
    Daniele Segato

    Daniele Segato

    1 year ago
    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
    Adam Powell

    Adam Powell

    1 year ago
    If you're looking to have Compose manage the presence or absence of an actor in your composition, the general pattern is:
    LaunchedEffect(dataSource) {
      dataSource.collect { event ->
        doSomethingWith(event)
      }
    }
    your instinct to not treat a stream of events as state using
    collectAsState()
    is spot on 👍