Hey I am working in kotlin flow in android. I noti...
# android
v
Hey I am working in kotlin flow in android. I noticed that my kotlin flow
collectLatest
is calling twice and sometimes even more. I printed the log inside my
collectLatest
function it print the log.
m
Mmmh, I'll try this : The repeatOnLifeCycle will create a new coroutine when the lifecycle you gave in parameter is at least the state of your app. If you say
Lifecycle.State.STARTED
, you'll have a new coroutine for states STARTED and RESUME. So, I would try to remove it because you already have the
launchWhenStarted
juste above.
v
@Max Ferrier I removed
repeatOnLifeCycle
this but it didn't work
m
You mean you still have your 2
time
or nothing ?
(And at the same time, according to the collectLatest's doc, it's normal to have 2 results.)
v
@Max Ferrier yes it calling 2 times
m
Normal. Everything works as it's written. You have a first value at
emptyList()
and a second one with
response.items
. In the doc, it says :
Copy code
flow {
    emit(1)
    delay(50)
    emit(2)
}.collectLatest { value ->
    println("Collecting $value")
    delay(100) // Emulate work
    println("$value collected")
}
In the collect, the delay time is longer than in the flow. So if you send 20 values in your flow every 50ms, but your collect can treat only one value data in 100ms, you'll only work with the final value. But if you send 20 values in your flow every 500ms, and your collect can still treat one value every 100ms, you'll work with the 20 values. EDIT : With the first value wich finish the process and end the coroutine. If your coroutine is not killed, you'll work with the 20 values. In my link below, at the end of the first value, the GlobalScope is not kept alive.
v
@Max Ferrier thanks a million for great explanation Is there anyway to remove
emptyList()
and my
collectLatest
will call only once? Is it possible in flow?
m
@Vivek Modi: The main goal of the flow is to be triggered for every new data. You still can add a test on your list
data.isNotEmpty()
v
okk great thanks
👌🏻 1
494 Views