Arpit Shukla
Arpit Shukla

Reputation: 10493

Is it ok to pass a Flow from one composable to another?

I have a view model which exposes a flow of events. I have that viewModel injected in a top level composable but I want to send the events to another composable (inside the top level composable). Something like this:

@Composable
fun MainScreen(viewModel: MyViewModel) {
    SomeComponent(viewModel.events) 
    // Other Stuff   
}

@Composable
fun SomeComponent(events: Flow<MyEvent>) { // MyEvent is a sealed class
    LaunchedEffect(Unit) {
        events.collect {
            // Process the events
        }
    }
    // Other stuff
}

The reason I am collecting the flow in SomeComponent and not MainScreen is because I need access to some internal state of SomeComponent (it's a ScaffoldState actually) for processing the events.

I wrote this code in my app and everything seems to be working but I am not sure if this is a good thing to do.
My question is:
Are there any drawbacks in this approach that I missed? What can possibly go wrong here?

Upvotes: 7

Views: 1505

Answers (1)

Johann
Johann

Reputation: 29877

Passing a flow as parameter is fine. There is nothing special about a flow. It's just another data source like anything else. If you didn't pass it in, you would have to come up with some other way of accessing it and that would probably result in breaking the uni-directional flow pattern that Composables should adhere to.

Upvotes: 3

Related Questions