When collecting a Kotlin flow inside an Activity o...
# android
m
When collecting a Kotlin flow inside an Activity or Fragement:
Copy code
override fun onCreate(…) {
 …
 scope.launch /* on Dispatchers.Main */ {
   viewModel.flow.collect { it ->
      uiElement.text = it
   }
 }
}
Is is better to do
launch(Dispatchers.Default)
and then wrap the UI operation in
withContext(Dispatchers.Main)
, or is there no practical difference since the collect is suspending and not blocking? If I would do more operations except setting the UI element, I would always do the approach with launch on Dispatchers.Default + withContext(Main), but here I really only update the UI on collect
a
m
Thank you for that link, I’ve not yet migrated to androidx to my shame, guess I should just do so soon
a
I see, well I guess in that case you could do it as posted, but you'll be receiving updates when activity is paused... all the way until your 'scope' is cancelled. But to answer your original question - it shouldnt matter I think
m
Thank you very much 🙂