Safely collecting hot flows from Android native UI

Photo: Merlene Goulet from Unsplash

Setup

Bug

Cause

lifecycleScope.launchWhenResumed {
viewModel.sourceFlow.collect {
binding.sourceFlow.text = it.toString() // Execution stops here
}
viewModel.transformedFlow.collect {
binding.transformedFlow.text = it.toString()
}
}

Fix

lifecycleScope.launchWhenResumed {
viewModel.sourceFlow.collect {
binding.sourceFlow.text = it.toString()
}
}

lifecycleScope.launchWhenResumed {
viewModel.transformedFlow.collect {
binding.transformedFlow.text = it.toString()
}
}

Learning

--

--

Android Developer@Instacart

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store