Using Produce to send emissions
- When we use produce, We explicitly do not need to
close
the channel.
- A produce block returns a channel reference, Which can be used by other coroutines to receive the values.
- Also to not that then the channels are active the enclosing co-routine is also active, And it completes once the channel is closed.
private var receiveChannel : ReceiveChannel<Superheroes> = Channel()
fun usingProduce() {
// Co-Routine - 1
viewModelScope.launch {
receiveChannel = produce {
send(Superheroes.Batman)
send(Superheroes.Superman)
send(Superheroes.Spiderman)
}
}
// Co-Routine - 2
viewModelScope.launch {
println("Is closed to receive -->"+ receiveChannel.isClosedForReceive)
receiveChannel.consumeEach { superHero ->
println(superHero)
}
println("Is closed to receive -->"+ receiveChannel.isClosedForReceive)
}
}
enum class Superheroes { Batman , Superman , Spiderman }
Is closed to receive -->false
Batman
Superman
Spiderman
Is closed to receive -->true