github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/utilities/event/example_scope_test.go (about)

     1  package event_test
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/neatio-net/neatio/utilities/event"
     8  )
     9  
    10  type divServer struct{ results event.Feed }
    11  type mulServer struct{ results event.Feed }
    12  
    13  func (s *divServer) do(a, b int) int {
    14  	r := a / b
    15  	s.results.Send(r)
    16  	return r
    17  }
    18  
    19  func (s *mulServer) do(a, b int) int {
    20  	r := a * b
    21  	s.results.Send(r)
    22  	return r
    23  }
    24  
    25  type App struct {
    26  	divServer
    27  	mulServer
    28  	scope event.SubscriptionScope
    29  }
    30  
    31  func (s *App) Calc(op byte, a, b int) int {
    32  	switch op {
    33  	case '/':
    34  		return s.divServer.do(a, b)
    35  	case '*':
    36  		return s.mulServer.do(a, b)
    37  	default:
    38  		panic("invalid op")
    39  	}
    40  }
    41  
    42  func (s *App) SubscribeResults(op byte, ch chan<- int) event.Subscription {
    43  	switch op {
    44  	case '/':
    45  		return s.scope.Track(s.divServer.results.Subscribe(ch))
    46  	case '*':
    47  		return s.scope.Track(s.mulServer.results.Subscribe(ch))
    48  	default:
    49  		panic("invalid op")
    50  	}
    51  }
    52  
    53  func (s *App) Stop() {
    54  	s.scope.Close()
    55  }
    56  
    57  func ExampleSubscriptionScope() {
    58  
    59  	var (
    60  		app  App
    61  		wg   sync.WaitGroup
    62  		divs = make(chan int)
    63  		muls = make(chan int)
    64  	)
    65  
    66  	divsub := app.SubscribeResults('/', divs)
    67  	mulsub := app.SubscribeResults('*', muls)
    68  	wg.Add(1)
    69  	go func() {
    70  		defer wg.Done()
    71  		defer fmt.Println("subscriber exited")
    72  		defer divsub.Unsubscribe()
    73  		defer mulsub.Unsubscribe()
    74  		for {
    75  			select {
    76  			case result := <-divs:
    77  				fmt.Println("division happened:", result)
    78  			case result := <-muls:
    79  				fmt.Println("multiplication happened:", result)
    80  			case <-divsub.Err():
    81  				return
    82  			case <-mulsub.Err():
    83  				return
    84  			}
    85  		}
    86  	}()
    87  
    88  	app.Calc('/', 22, 11)
    89  	app.Calc('*', 3, 4)
    90  
    91  	app.Stop()
    92  	wg.Wait()
    93  
    94  }