By the docs, I should never collect the flow from launch or launchIn, but if I try to change my code to be executed from inside the repeatOnLifecycle
it is just being ignored.
This is the code I'm using right now in my Fragment
:
private fun observeUI() {
viewLifecycleOwner.lifecycleScope.launch {
launch {
viewModel.uiState.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.collect { uiState ->
uiState.error?.let { showErrorAlert(it)}
uiState.success?.let { handleSuccessState(it) }
handleLoadingState(uiState.isLoading)
}
}
repeatOnLifecycle(Lifecycle.State.STARTED) {
scanner.barcode.collect { handleScannedBarcode(it) }
}
}
}
The function is called from onViewCreated
and works as have to.
But if I try to refactor the function by moving the UI collect in repeatOnLifecycle
that will stop working.
What I'm trying to do is this, and I've yet tried to use CREATED
instead of STARTED
:
private fun observeUI() {
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.flowWithLifecycle(viewLifecycleOwner.lifecycle)
.collect { uiState ->
uiState.error?.let { showErrorAlert(it)}
uiState.success?.let { handleSuccessState(it) }
handleLoadingState(uiState.isLoading)
}
scanner.barcode.collect { handleScannedBarcode(it) }
}
}
}