---
# System prepended metadata

title: The right way to collect/observe from LiveData/Flow in ViewModel

---

# The right way to collect/observe from LiveData/Flow in ViewModel

### Flow
```kotlin=
// Declare the flow
private val canGoBack = MutableStateFlow(true)

// Expose function to collect
fun collectCanGoBackFlow(
    viewLifecycleOwner: LifecycleOwner,
    flowCollector: FlowCollector<Boolean>,
) {
    viewLifecycleOwner.lifecycleScope.launch {
        canGoBack.flowWithLifecycle(viewLifecycleOwner.lifecycle)
        .collect(flowCollector)
    }
}

// Emit it
viewModelScope.launch {
    canGoBack.emit(false)
}

// Collect from UI
viewModel.collectCanGoBackFlow(viewLifecycleOwner) {
    isVisible = it
}

// Or extension
fun <T : Any?> LifecycleOwner.collectFlowWithLifeCycle(
    flow: Flow<T>,
    flowCollector: FlowCollector<T>,
) {
    lifecycleScope.launch {
        flow.flowWithLifecycle(lifecycle).collect(flowCollector)
    }
}

// Then collect on VM using the extension
fun collectCanGoBackFlow(
    viewLifecycleOwner: LifecycleOwner,
    collectorBlock: FlowCollector<Boolean>,
) {
    viewLifecycleOwner.collectFlowWithLifeCycle(canGoBack, collectorBlock)
}
```

### LiveData
```kotlin=
// Declare the livedata
private val registerAccountUiStateLiveData = MutableLiveData<RegisterAccountUiState>()

// Expose function to observe
fun observeRegisterAccountLiveData(
    lifecycleOwner: LifecycleOwner,
    observingBlock: (RegisterAccountUiState) -> Unit,
) {
    registerAccountUiStateLiveData.observe(lifecycleOwner, observingBlock)
}

// Post it
viewModelScope.launch {
    registerAccountUiStateLiveData.postValue(...)
}

// Observe from UI
viewModel.observeRegisterAccountLiveData(viewLifecycleOwner) {
    ...
}
```