0

What different performance when uiState init with collectAsState and use by or = ?

val uiState by viewModel.uiState.collectAsState()

vs

val uiState = viewModel.uiState.collectAsState()
Rumit Patel
  • 8,830
  • 18
  • 51
  • 70
Leila_ygb
  • 51
  • 4

1 Answers1

1

It basically allows you to save using the getter in order to read the value of your state, check the example below.

In your view model you can have the state like this

val state: StateFlow<MainStates>

and then in your view if you use the by operator it allows you to read directly the state without the ".value"

val state by viewModel.state.collectAsStateWithLifecycle()

when(state) {
    is MainStates.Loading -> {
      CircularProgressIndicator()
    }
    is MainStates.LoadedData -> {
      MainComposable((state as MainStates.LoadedData).data)
    }
  }

In case you use "=" then you would need to the getter ("state.value") to access the value.

Luis Pascual
  • 256
  • 1
  • 3
  • 13