example_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package event
  17. import "fmt"
  18. func ExampleTypeMux() {
  19. type someEvent struct{ I int }
  20. type otherEvent struct{ S string }
  21. type yetAnotherEvent struct{ X, Y int }
  22. var mux TypeMux
  23. // Start a subscriber.
  24. done := make(chan struct{})
  25. sub := mux.Subscribe(someEvent{}, otherEvent{})
  26. go func() {
  27. for event := range sub.Chan() {
  28. fmt.Printf("Received: %#v\n", event.Data)
  29. }
  30. fmt.Println("done")
  31. close(done)
  32. }()
  33. // Post some events.
  34. mux.Post(someEvent{5})
  35. mux.Post(yetAnotherEvent{X: 3, Y: 4})
  36. mux.Post(someEvent{6})
  37. mux.Post(otherEvent{"whoa"})
  38. // Stop closes all subscription channels.
  39. // The subscriber goroutine will print "done"
  40. // and exit.
  41. mux.Stop()
  42. // Wait for subscriber to return.
  43. <-done
  44. // Output:
  45. // Received: event.someEvent{I:5}
  46. // Received: event.someEvent{I:6}
  47. // Received: event.otherEvent{S:"whoa"}
  48. // done
  49. }