androidkotlinkotlin-stateflow

Can't access MutableStateFlow value in activity


I Have the following sealed class

sealed class SearchedState {
    data class FoundCrag(val crag: Crag): SearchedState()
    data class FoundZone(val zone: Zone) : SearchedState()
    data class FoundRoute(val route: Route): SearchedState()
    data object NotFound: SearchedState()
}

In the ViewModel I have this state

private var _state = MutableStateFlow<SearchedState>(SearchedState.NotFound)
val state: StateFlow<SearchedState> = _state

and I assing a value like this

_state.value = SearchedState.FoundCrag(crag)

The problem is that, On the activity I can't access to the object crag that I'm assigning on the VM.

This is what I do on the activity.

mainViewModel.search(searched)

            when (mainViewModel.state.value) {
                is SearchedState.FoundCrag -> {
                    val intent = Intent("independent.dev.ui.cragmenuactivity")
                    val bundle = Bundle()
                    bundle.putSerializable("chosenCrag", it)
                    intent.putExtras(bundle)
                    startActivity(intent)
                }
               .
               .
               .
            }

In the bundle I wanna pass the crag object that it's supposed I'm getting from VM but it is not recognized.

What I'm doing wrong??


Solution

  • Introduce a when statement scoped variable correctly destruct the state object:

    when (val state = mainViewModel.state.value) {
        is SearchedState.FoundCrag -> {
            val intent = Intent("independent.dev.ui.cragmenuactivity")
            val bundle = Bundle()
            bundle.putSerializable("chosenCrag", state.crag) // Access crag from state
            intent.putExtras(bundle)
            startActivity(intent)
        }
    }