6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

KotlinのFlow.onEachの挙動

6
Posted at

多分collectされるたびに別ストリームになるのでonEachは複数回呼ばれている

class EventBus {
    private val _event = MutableSharedFlow<Int>()
    val event: Flow<Int> = _event.onEach { println("onEach $it") }

    suspend fun emit(i: Int) {
        println("EventBus emit $i")
        _event.emit(i)
    }
}

class A(val eventBus: EventBus) {
    suspend fun start() {
        println("A start")
        eventBus.event.collect {
            println("A collect $it")
        }
    }
}

class B(val eventBus: EventBus) {
    suspend fun start() {
        println("B start")
        eventBus.event.collect {
            println("B collect $it")
        }
    }
}

val eventBus = EventBus()
val a = A(eventBus)
val b = B(eventBus)

println("start")
runBlocking {
    val jobA = launch {
        a.start()
    }
    val jobB = launch {
        b.start()
    }
    delay(1000)
    eventBus.emit(1)
    jobA.cancel()
    jobB.cancel()
}
println("end")

期待してた動作

start
A start
B start
EventBus emit 1
onEach 1
A collect 1
B collect 1
end

実際の動作

start
A start
B start
EventBus emit 1
onEach 1
A collect 1
onEach 1
B collect 1
end

onEachが複数回呼ばれている

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?