-
Notifications
You must be signed in to change notification settings - Fork 22
End to end communication types in channels
Devrath edited this page Jan 18, 2024
·
10 revisions
Contents |
---|
1-N --> Communicaton - Fan-Out approach |
N-1 --> Communicaton - Fan-In approach |
N-N --> Communication - Load balancers |
- Here basically there is one producer and multiple consumers.
- Note in the output when the consumer is consuming an emission or if it's suspended, another consumer receives the emission.
- Also you can observe all the consumers share the emissions meaning an emission received by one consumer is not received in another emission.
- We call it
Fan-Out
approach
output
Consumer-1 <-> (1-n) : ----> 1
Consumer-2 <-> (1-n) : ----> 3
Consumer-3 <-> (1-n) : ----> 5
Consumer-2 <-> (1-n) : ----> 7
Consumer-3 <-> (1-n) : ----> 9
Code
private var one_to_n_channel : ReceiveChannel<Int> = Channel()
fun usingOneToMany() {
viewModelScope.launch {
// Producer -1
one_to_n_channel = produce(capacity = UNLIMITED){
repeat(10){ currentValue -> send(currentValue) }
}
}
viewModelScope.launch {
// Coroutine - 1
viewModelScope.launch {
// Consumer - 1
one_to_n_channel.consumeEach {
println("Consumer-1 <-> (1-n) : ----> $it")
delay(300)
}
}
// Coroutine - 2
viewModelScope.launch {
// Consumer - 2
one_to_n_channel.consumeEach {
println("Consumer-2 <-> (1-n) : ----> $it")
delay(100)
}
}
// Coroutine - 3
viewModelScope.launch {
// Consumer - 3
one_to_n_channel.consumeEach {
println("Consumer-3 <-> (1-n) : ----> $it")
delay(150)
}
}
}
}
- Here there are multiple producers and just one consumer.
- They use one channel for their mode of communication.
- We call it
Fan-In
approach
Output
Consumer <-> (N-1) : ----> FromProducer-1 0
Consumer <-> (N-1) : ----> FromProducer-2 0
Consumer <-> (N-1) : ----> FromProducer-2 1
Consumer <-> (N-1) : ----> FromProducer-1 1
Consumer <-> (N-1) : ----> FromProducer-2 2
Consumer <-> (N-1) : ----> FromProducer-1 2
Code
private var n_to_one_channel : Channel<String> = Channel()
fun usingManyToOne() {
viewModelScope.launch {
// Producer -1
val firstProducer = viewModelScope.async {
repeat(3){ currentValue ->
n_to_one_channel.send("FromProducer-1 $currentValue")
delay(150)
}
}
// Producer -2
val secondProducer = viewModelScope.async {
repeat(3){ currentValue ->
n_to_one_channel.send("FromProducer-2 $currentValue")
delay(100)
}
}
awaitAll(secondProducer,firstProducer)
}
// Consumer-1
viewModelScope.launch {
n_to_one_channel.consumeEach {
println("Consumer <-> (N-1) : ----> $it")
}
}
}