Skip to content

Instantly share code, notes, and snippets.

@iKunalChhabra
Created November 29, 2024 09:11
Show Gist options
  • Save iKunalChhabra/0e72c1617443107e7dca0ba3ac9fa6fc to your computer and use it in GitHub Desktop.
Save iKunalChhabra/0e72c1617443107e7dca0ba3ac9fa6fc to your computer and use it in GitHub Desktop.
Consumer Producer in Kotlin Coroutine using channels
package com.example
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlin.random.Random
fun main(){
val channel = Channel<Int>(2)
runBlocking {
launch { produceValue(channel, 5) }
launch { consumeValue(channel, 5) }
}
}
suspend fun produceValue(channel: Channel<Int>, idx: Int) {
for (i in 1..idx) {
val number = Random.nextInt()
println("$i: Sending $number")
channel.send(number)
}
}
suspend fun consumeValue(channel: Channel<Int>, idx: Int) {
for (i in 1..idx) {
delay(500)
println("$i: Received ${channel.receive()}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment