Home > Net >  LiveData (not Flow) with states
LiveData (not Flow) with states

Time:11-30

I have a huge project and I need to refactor code to LiveData (not Flow). I have an Order and states in ViewModel. I cannot receive this Order in Activity when I observe it. How can I do this? This is my View Model:

private var _basicModel: MutableLiveData<OrderUiState> = MutableLiveData()
val basicModel: LiveData<OrderUiState> get() = _basicModel

sealed class OrderUiState {
    object Loading : OrderUiState()
    data class OrderFail(val message: String) : OrderUiState()
    data class OrderSuccess(val order: Order) : OrderUiState()
}

 fun getOrder(orderId: String) {

    viewModelScope.launch {

        _basicModel.value = OrderUiState.Loading

        getOrderUseCase.execute(orderId, { order ->
            _basicModel.value = OrderUiState.OrderSuccess(order)
        }
   }

And now I cannot to get to Order, when I have Succes Sate. My code want from me in Activity order, but I thought, that whan it is success, there it will be, but isn't?

viewModel.basicModel.observe(this) { order ->

        when(order){
            OrderViewModel.OrderUiState.OrderSuccess(here he want from me order... )
        }

    }

Can I get to order from this code?

CodePudding user response:

You can do it this way:

viewModel.basicModel.observe(this) { uiState ->
    when(uiState) {
        is OrderViewModel.OrderUiState.OrderSuccess -> {
            val order = uiState.order
            // Use the order here
        }
    }
}
  • Related