luminyra
Guides

Asynchronous sources and termination

Consume channels and timers, merge multiple inputs, and handle the first terminal error.

Read a channel

FromChannel completes when its channel closes. In the example, the sender closes the channel, Observable.Map uppercases each value, and Observable.Collect collects them. A production sender should also support cancellation so it does not remain blocked on a send after the subscription ends.

rx/examples/async/main.go
// The source completes when the channel is closed.
steps := make(chan string)
go func() {
	defer close(steps)
	for _, s := range []string{"build", "test", "deploy"} {
		steps <- s
	}
}()
upper, err := rx.FromChannel(steps).Map(strings.ToUpper).Collect(ctx)
View on GitHub

Stop a timed stream

Interval continues emitting values. The example consumes it with Observable.All and exits when the target value arrives. The iterator stops the source and waits for it to exit. A context deadline can also limit the subscription.

rx/examples/async/main.go
// Interval never completes on its own. Breaking out of the range loop
// stops the timer and waits for it to exit.
for tick, err := range rx.Interval(10 * time.Millisecond).All(ctx) {
	if err != nil {
		fmt.Println("error:", err)
		break
	}
	fmt.Println("tick", tick)
	if tick == 2 {
		break
	}
}
View on GitHub

Merge sources and propagate errors

Merge combines multiple sources and terminates with the first source error. Use Fail to create a source that emits an error. When you collect a stream, values already received come back with the error so you can handle partial results explicitly.

rx/examples/async/main.go
// When any source fails, Merge ends with that error; the values received
// so far are still returned.
merged, err := rx.Merge(
	rx.Just(1, 2),
	rx.Fail[int](errors.New("downstream service unavailable")),
	rx.Just(3, 4),
).Collect(ctx)
View on GitHub

On this page