Pawandeep Singh
Pawandeep Singh

Reputation: 269

Jetpack Compose: What's the best practice for collecting StateFlow - in parent or child composable?

I have a Compose screen structure where ComposableA contains ComposableB and ComposableC. ComposableC needs data from a StateFlow in the ViewModel. I'm trying to determine the best approach for collecting this StateFlow.

Here are the two approaches I'm considering:

Approach 1: Collecting in Parent (ComposableA) and passing state down kotlin

class MyViewModel : ViewModel() {
    private val _userState = MutableStateFlow<String>("")
    val userState = _userState.asStateFlow()
}

@Composable
fun ComposableA(viewModel: MyViewModel) {
    val userState by viewModel.userState.collectAsStateWithLifecycle()
    
    Column {
        ComposableB()
        ComposableC(userData = userState)
    }
}

@Composable
fun ComposableC(userData: String) {
    Text(text = userData)

Approach 2: Passing ViewModel to child and collecting there kotlin

@Composable
fun ComposableA(viewModel: MyViewModel) {
    Column {
        ComposableB()
        ComposableC(viewModel = viewModel)
    }
}

@Composable
fun ComposableC(viewModel: MyViewModel) {
    val userState by viewModel.userState.collectAsStateWithLifecycle()
    Text(text = userState)
}

Which approach is considered better practice ?

Upvotes: 0

Views: 38

Answers (0)

Related Questions