github.com/freiheit-com/kuberpult@v1.24.2-0.20240328135542-315d5630abe6/services/cd-service/pkg/notify/notify.go (about)

     1  /*This file is part of kuberpult.
     2  
     3  Kuberpult is free software: you can redistribute it and/or modify
     4  it under the terms of the Expat(MIT) License as published by
     5  the Free Software Foundation.
     6  
     7  Kuberpult 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
    10  MIT License for more details.
    11  
    12  You should have received a copy of the MIT License
    13  along with kuberpult. If not, see <https://directory.fsf.org/wiki/License:Expat>.
    14  
    15  Copyright 2023 freiheit.com*/
    16  
    17  package notify
    18  
    19  import "sync"
    20  
    21  type Notify struct {
    22  	mx       sync.Mutex
    23  	listener map[chan struct{}]struct{}
    24  }
    25  
    26  type Unsubscribe = func()
    27  
    28  func (n *Notify) Subscribe() (<-chan struct{}, Unsubscribe) {
    29  	ch := make(chan struct{}, 1)
    30  	ch <- struct{}{}
    31  
    32  	n.mx.Lock()
    33  	defer n.mx.Unlock()
    34  	if n.listener == nil {
    35  		n.listener = map[chan struct{}]struct{}{}
    36  	}
    37  
    38  	n.listener[ch] = struct{}{}
    39  	return ch, func() {
    40  		n.mx.Lock()
    41  		defer n.mx.Unlock()
    42  		delete(n.listener, ch)
    43  	}
    44  }
    45  
    46  func (n *Notify) Notify() {
    47  	n.mx.Lock()
    48  	defer n.mx.Unlock()
    49  	for ch := range n.listener {
    50  		select {
    51  		case ch <- struct{}{}:
    52  		default:
    53  		}
    54  	}
    55  }