Created
October 24, 2017 04:15
-
-
Save logicalguess/045a6b0d17afb0e41cb661d5027d3452 to your computer and use it in GitHub Desktop.
Event-driven components in Go.
This file contains 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 main | |
import ( | |
"fmt" | |
"time" | |
) | |
type G interface{} | |
func producer(ch chan []G, d time.Duration) { | |
var i int | |
for { | |
ch <- []G{"aaaa", "bbb"} | |
ch <- []G{3, 7} | |
ch <- []G{"cccccc", "dddddd"} | |
ch <- []G{21, 5} | |
i++ | |
time.Sleep(d) | |
} | |
} | |
func reader(out chan int) { | |
for x := range out { | |
fmt.Println(x) | |
} | |
} | |
type Component struct { | |
state G | |
update func(G, G) G | |
value func(G) int | |
} | |
func (c * Component) connect(source chan []G, sink chan int) { | |
for data := range source { | |
for _, word := range data { | |
c.state = c.update(c.state, word) | |
if sink != nil { | |
sink <- c.value(c.state) | |
} | |
} | |
} | |
} | |
func main() { | |
updateFn := func(s G, i G) G { | |
var ret G | |
switch i.(type) { | |
case string: | |
ret = s.(int) + len(i.(string)) | |
case int: | |
ret = s.(int) + i.(int) | |
} | |
return ret | |
} | |
valueFn := func(s G) int { | |
return s.(int) | |
} | |
c := Component{state: 0, update: updateFn, value: valueFn} | |
source := make(chan []G) | |
sink := make(chan int) | |
go producer(source, 500*time.Millisecond) | |
go reader(sink) | |
c.connect(source, sink) | |
source1 := make(chan []G) | |
go producer(source1, 200*time.Millisecond) | |
c.connect(source1, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment