olebedev / emitter

Emits events in Go way, with wildcard, predicates, cancellation possibilities and many other good wins
Other
505 stars 34 forks source link

Emitting in listener does not work #7

Open eyudkin opened 6 years ago

eyudkin commented 6 years ago

There is example: https://play.golang.org/p/d0jXdhwwfrU

Output:

*: Event received: a
a: Event received: a
ivan1993spb commented 6 years ago

ping @olebedev

graham commented 6 years ago

@tensor146

Emitting seems to block the go-routine you're calling from, but you can emit from another go-routine

package main

import (
    "fmt"

    "github.com/olebedev/emitter"
)

func main() {
    e := &emitter.Emitter{}
    go func() {
        <-e.Emit("change", 42) // wait for the event sent successfully
        <-e.Emit("change", 37)
        e.Off("*") // unsubscribe any listeners
    }()

    for event := range e.On("change") {
        fmt.Println(event.Int(0)) // cast the first argument to int
        go func() {
            e.Emit("change", 100)
        }()
    }
    // listener channel was closed
}