github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/event/example_test.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  package event
    13  
    14  import "fmt"
    15  
    16  func ExampleTypeMux() {
    17  	type someEvent struct{ I int }
    18  	type otherEvent struct{ S string }
    19  	type yetAnotherEvent struct{ X, Y int }
    20  
    21  	var mux TypeMux
    22  
    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  
    34  	// Post some events.
    35  	mux.Post(someEvent{5})
    36  	mux.Post(yetAnotherEvent{X: 3, Y: 4})
    37  	mux.Post(someEvent{6})
    38  	mux.Post(otherEvent{"whoa"})
    39  
    40  	// Stop closes all subscription channels.
    41  	// The subscriber goroutine will print "done"
    42  	// and exit.
    43  	mux.Stop()
    44  
    45  	// Wait for subscriber to return.
    46  	<-done
    47  
    48  	// Output:
    49  	// Received: event.someEvent{I:5}
    50  	// Received: event.someEvent{I:6}
    51  	// Received: event.otherEvent{S:"whoa"}
    52  	// done
    53  }