Created
November 29, 2024 09:11
-
-
Save iKunalChhabra/0e72c1617443107e7dca0ba3ac9fa6fc to your computer and use it in GitHub Desktop.
Consumer Producer in Kotlin Coroutine using channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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