Why does kotlin flow 'onStart' method not call immediately after 'collect' is called?

63 Views Asked by At

example code:

suspend fun main() {
  val start = System.currentTimeMillis()

  flowOf("flow value")   // 1
    .onStart {
      println("onStart delta: ${System.currentTimeMillis() - start}ms")  // 2
      emit("onStart value")
    }
    .flowOn(Dispatchers.IO)
    .collectLatest { println("collect: $it") }  // 3

  println("Finish")
}

① Create a simple flow that emit a String value.

② Make flow#onStart method and calculate delta time when method is invoked.

③ collect this flow immediately.

The result shows:

onStart delta: 96ms
collect: onStart value
collect: flow 
Finish

try this on kotlin playground

Why onStart take so long time to invoke? Logic code in my app like this:

  flow
    .onEach { saveToCache(it) }
    .onStart { emit(loadFromCache()) }

I use onStart load cache. But on some old phone, it takes 250+ms to execute onStart method, Why is so slow, Any other way to do that?

0

There are 0 best solutions below