github.com/klaytn/klaytn@v1.12.1/event/example_feed_test.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2016 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from event/example_feed_test.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package event_test
    22  
    23  import (
    24  	"fmt"
    25  
    26  	"github.com/klaytn/klaytn/event"
    27  )
    28  
    29  func ExampleFeed_acknowledgedEvents() {
    30  	// This example shows how the return value of Send can be used for request/reply
    31  	// interaction between event consumers and producers.
    32  	var feed event.Feed
    33  	type ackedEvent struct {
    34  		i   int
    35  		ack chan<- struct{}
    36  	}
    37  
    38  	// Consumers wait for events on the feed and acknowledge processing.
    39  	done := make(chan struct{})
    40  	defer close(done)
    41  	for i := 0; i < 3; i++ {
    42  		ch := make(chan ackedEvent, 100)
    43  		sub := feed.Subscribe(ch)
    44  		go func() {
    45  			defer sub.Unsubscribe()
    46  			for {
    47  				select {
    48  				case ev := <-ch:
    49  					fmt.Println(ev.i) // "process" the event
    50  					ev.ack <- struct{}{}
    51  				case <-done:
    52  					return
    53  				}
    54  			}
    55  		}()
    56  	}
    57  
    58  	// The producer sends values of type ackedEvent with increasing values of i.
    59  	// It waits for all consumers to acknowledge before sending the next event.
    60  	for i := 0; i < 3; i++ {
    61  		acksignal := make(chan struct{})
    62  		n := feed.Send(ackedEvent{i, acksignal})
    63  		for ack := 0; ack < n; ack++ {
    64  			<-acksignal
    65  		}
    66  	}
    67  	// Output:
    68  	// 0
    69  	// 0
    70  	// 0
    71  	// 1
    72  	// 1
    73  	// 1
    74  	// 2
    75  	// 2
    76  	// 2
    77  }