github.com/ethereum/go-ethereum@v1.14.3/event/multisub.go (about)

     1  // Copyright 2023 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  // JoinSubscriptions joins multiple subscriptions to be able to track them as
    20  // one entity and collectively cancel them of consume any errors from them.
    21  func JoinSubscriptions(subs ...Subscription) Subscription {
    22  	return NewSubscription(func(unsubbed <-chan struct{}) error {
    23  		// Unsubscribe all subscriptions before returning
    24  		defer func() {
    25  			for _, sub := range subs {
    26  				sub.Unsubscribe()
    27  			}
    28  		}()
    29  		// Wait for an error on any of the subscriptions and propagate up
    30  		errc := make(chan error, len(subs))
    31  		for i := range subs {
    32  			go func(sub Subscription) {
    33  				select {
    34  				case err := <-sub.Err():
    35  					if err != nil {
    36  						errc <- err
    37  					}
    38  				case <-unsubbed:
    39  				}
    40  			}(subs[i])
    41  		}
    42  
    43  		select {
    44  		case err := <-errc:
    45  			return err
    46  		case <-unsubbed:
    47  			return nil
    48  		}
    49  	})
    50  }