https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

pdegand

08/31/2018, 3:20 PM
My usecase is to build a lazy cache with a ConflatedBroadcastChannel where when a subscriber is suspending on
receive()
, some code that will send stuff into the channel is executed
b

bdawg.io

08/31/2018, 7:43 PM
You could wrap your channel to do something on receive
Copy code
val delegateChannel = ConflatedBroadcastChannel<Int>()
suspend fun ConflatedBroadcastChannel<Int>.populate() {
    send(10)
}

val subscription = delegateChannel.openSubscription()
val channel = object : ReceiveChannel<Int> by subscription {
    private val populated = AtomicBoolean(false)

    override suspend fun receive() = this.run {
        populate()
        subscription.receive()
    }

    private suspend fun populate() {
        if (!populated.get()) {
            delegateChannel.populate()
            populated.set(true)
        }
    }
}
5 Views