github.com/fxsjy/go-ethereum@v1.8.4-0.20180410143526-2e247705cd27/event/example_test.go (about)

     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  
    17  package event
    18  
    19  import "fmt"
    20  
    21  func ExampleTypeMux() {
    22  	type someEvent struct{ I int }
    23  	type otherEvent struct{ S string }
    24  	type yetAnotherEvent struct{ X, Y int }
    25  
    26  	var mux TypeMux
    27  
    28  	// Start a subscriber.
    29  	done := make(chan struct{})
    30  	sub := mux.Subscribe(someEvent{}, otherEvent{})
    31  	go func() {
    32  		for event := range sub.Chan() {
    33  			fmt.Printf("Received: %#v\n", event.Data)
    34  		}
    35  		fmt.Println("done")
    36  		close(done)
    37  	}()
    38  
    39  	// Post some events.
    40  	mux.Post(someEvent{5})
    41  	mux.Post(yetAnotherEvent{X: 3, Y: 4})
    42  	mux.Post(someEvent{6})
    43  	mux.Post(otherEvent{"whoa"})
    44  
    45  	// Stop closes all subscription channels.
    46  	// The subscriber goroutine will print "done"
    47  	// and exit.
    48  	mux.Stop()
    49  
    50  	// Wait for subscriber to return.
    51  	<-done
    52  
    53  	// Output:
    54  	// Received: event.someEvent{I:5}
    55  	// Received: event.someEvent{I:6}
    56  	// Received: event.otherEvent{S:"whoa"}
    57  	// done
    58  }