v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/broadcast/butil/broadcastchannel.go (about)

     1  package butil
     2  
     3  import (
     4  	"sync"
     5  
     6  	"v8.run/go/exp/broadcast"
     7  )
     8  
     9  var broadcastChannelMap = sync.Map{}
    10  
    11  type BroadcastChannelTopic struct {
    12  	s         *broadcast.Subscription[interface{}]
    13  	name      string
    14  	OnMessage func(v interface{})
    15  }
    16  
    17  func BroadcastChannel(name string) *BroadcastChannelTopic {
    18  	v, ok := broadcastChannelMap.Load(name)
    19  	if v != ok {
    20  		v, _ = broadcastChannelMap.LoadOrStore(name, broadcast.NewTopic[interface{}]())
    21  	}
    22  
    23  	bt := &BroadcastChannelTopic{
    24  		name: name,
    25  	}
    26  
    27  	s := v.((*broadcast.Topic[interface{}])).Subscribe(func(v interface{}) {
    28  		o := bt.OnMessage
    29  		if o != nil {
    30  			o(v)
    31  		}
    32  	})
    33  	bt.s = s
    34  
    35  	return bt
    36  }
    37  
    38  func (bt BroadcastChannelTopic) Name() string {
    39  	return bt.name
    40  }
    41  
    42  func (bt BroadcastChannelTopic) PostMessage(msg interface{}) {
    43  	bt.s.Topic().Broadcast(msg)
    44  	return
    45  }
    46  
    47  func (bt BroadcastChannelTopic) Close() {
    48  	bt.s.Unsubscribe()
    49  }