Wednesday, 6 November 2013

Dynamic Input Channels

Suppose a function produces some output on a channel, and that the output of this function is to be conditionally consumed dependant on the current system state. Also, lets suppose, the system contains a restriction in that the output channel of the producer function must remain fixed.

The question is then, how to route the output to the correct consuming logic, without reassigning the output channel.

One solution is to dynamically assign the consumer's input channel. Go provides a mechanism for this; the channel itself.

s := make(chan chan int)
c := make(chan int)
for {
    select {
    case c = <- s:
    case v := <- c:
        logic(v)                                                                                                  
    }
}  
        
With this logic in place the consumer's input channel can be dynamically reassigned whilst the producer remains agnostic. 

Here is a complete example of the mechanism at work.