https://kotlinlang.org logo
#android
Title
# android
v

voben

12/05/2019, 6:46 PM
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

tseisel

12/05/2019, 10:25 PM
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

voben

12/05/2019, 10:38 PM
Thanks
Is this better than doing?
Copy code
scope.launch { flow.collect() }
Is the second one more kotlin-y than the first?
d

Daniel

12/09/2019, 8:28 AM
it’s more kotlin-y i guess ..there’s no diff
t

tseisel

12/09/2019, 8:54 AM
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
2 Views