github.com/codingfuture/orig-energi3@v0.8.4/event/example_feed_test.go (about)

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