example_feed_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2016 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_test
  17. import (
  18. "fmt"
  19. "github.com/ethereum/go-ethereum/event"
  20. )
  21. func ExampleFeed_acknowledgedEvents() {
  22. // This example shows how the return value of Send can be used for request/reply
  23. // interaction between event consumers and producers.
  24. var feed event.Feed
  25. type ackedEvent struct {
  26. i int
  27. ack chan<- struct{}
  28. }
  29. // Consumers wait for events on the feed and acknowledge processing.
  30. done := make(chan struct{})
  31. defer close(done)
  32. for i := 0; i < 3; i++ {
  33. ch := make(chan ackedEvent, 100)
  34. sub := feed.Subscribe(ch)
  35. go func() {
  36. defer sub.Unsubscribe()
  37. for {
  38. select {
  39. case ev := <-ch:
  40. fmt.Println(ev.i) // "process" the event
  41. ev.ack <- struct{}{}
  42. case <-done:
  43. return
  44. }
  45. }
  46. }()
  47. }
  48. // The producer sends values of type ackedEvent with increasing values of i.
  49. // It waits for all consumers to acknowledge before sending the next event.
  50. for i := 0; i < 3; i++ {
  51. acksignal := make(chan struct{})
  52. n := feed.Send(ackedEvent{i, acksignal})
  53. for ack := 0; ack < n; ack++ {
  54. <-acksignal
  55. }
  56. }
  57. // Output:
  58. // 0
  59. // 0
  60. // 0
  61. // 1
  62. // 1
  63. // 1
  64. // 2
  65. // 2
  66. // 2
  67. }