In android, if I launch a coroutine from my fragme...
# android
v
In android, if I launch a coroutine from my fragment to collect a flow. Should I be calling this with
launch
,
launchWhenStarted
or
launchWhenResumed
. Assuming I’m calling this in the fragment’s
onViewCreated
Copy code
viewLifecycleOwner.lifecycleScope.launchWhenResumed { }
t
It all depends on what you do in the final
collect
block. I'd say that all three are roughly equivalent in your case. You can also use
flow.onEach { ... }.launchIn(viewLifecycleOwner.lifecycleScope)
v
Thanks
Is this better than doing?
Copy code
scope.launch { flow.collect() }
Is the second one more kotlin-y than the first?
d
it’s more kotlin-y i guess ..there’s no diff
t
In fact,
flow.launchIn(scope)
does exactly the same thing as
scope.launch { flow.collect() }
. You may prefer the former because it could be called in the same operator chain:
Copy code
flowOf(0, 1, 2, 3)
    .filter { it % 2 == 0 }
    .map { it * it }
    .launchIn(scope)
VS
Copy code
val flow = flowOf(0, 1, 2, 3)
    .filter { it % 2 == 0 }
    .map { it * it }
scope.launch { flow.collect() }
👍 1