Bridge Flattens Channel Of Channels

Flatten a stream of streams with bridge: consume <-chan (<-chan T), drain each source under the same done, and yield one merged result channel.

GoData Fetching

Code

gosnippet
56 lines
package main

import "fmt"

// bridge flattens a stream of streams(通道的通道 channel of channels):
// 外层取出每个源 channel,内层 drain 排空后取下一个
func bridge[T any](done <-chan struct{}, sources <-chan (<-chan T)) <-chan T {
	out := make(chan T)
	go func() {
		defer close(out)
		for {
			select {
			case <-done:
				return
			case src, ok := <-sources:
				if !ok {
					return
				}
		drain:
			for {
				select {
				case <-done:
					return
				case v, ok := <-src:
					if !ok {
						break drain // 源已关闭:取下一个源,而不是退出整个 bridge
					}
					select {
					case out <- v:
					case <-done:
						return
					}
				}
			}
			}
		}
	}()
	return out
}

func main() {
	done := make(chan struct{})
	first := make(chan string, 1)
	first <- "wal-1"
	close(first)
	second := make(chan string, 1)
	second <- "wal-2"
	close(second)
	sources := make(chan (<-chan string), 2)
	sources <- first
	sources <- second
	close(sources)
	for v := range bridge(done, sources) {
		fmt.Println("merged:", v)
	}
}

Following the data

Bridge Flattens Channel Of Channels comes down to the function main.

Iteration happens inside for — everything outside it runs once. Execution fans onto a goroutine and re-converges through a channel handoff. Cleanup is attached with defer, so it runs on every exit path of the function.

Points of care

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

Printed lines carry labels — (merged:) — pointing back to the operation behind each.

Key statements

sources := make(chan (<-chan string), 2)
for v := range bridge(done, sources) {
	fmt.Println("merged:", v)
}
done := make(chan struct{})

Interactive Tools for This Topic

FAQ

What does Bridge Flattens Channel Of Channels print when run?
Invoke the file as-is — the `merged:` prefixes identify which step printed each line.