orElse

If the primary source completes without emitting any elements, the elements from the secondary source are emitted.

Fan-in operators

Signature

Source.orElseSource.orElse Flow.orElseFlow.orElse

Description

If the primary source completes without emitting any elements, the elements from the secondary source are emitted. If the primary source emits any elements the secondary source is cancelled.

Note that both sources are materialized directly and the secondary source is backpressured until it becomes the source of elements or is cancelled.

Signal errors downstream, regardless which of the two sources emitted the error.

Example

Scala
sourceval source1 = Source(List("First source"))
val source2 = Source(List("Second source"))
val emptySource = Source.empty[String]

source1.orElse(source2).runWith(Sink.foreach(println))
// this will print "First source"

emptySource.orElse(source2).runWith(Sink.foreach(println))
// this will print "Second source"
Java
sourceimport org.apache.pekko.stream.javadsl.Keep;
import org.apache.pekko.stream.javadsl.Source;
import org.apache.pekko.stream.javadsl.Sink;

import java.util.*;

Source<String, NotUsed> source1 = Source.from(Arrays.asList("First source"));
Source<String, NotUsed> source2 = Source.from(Arrays.asList("Second source"));
Source<String, NotUsed> emptySource = Source.empty();

source1.orElse(source2).runForeach(System.out::println, system);
// this will print "First source"

emptySource.orElse(source2).runForeach(System.out::println, system);
// this will print "Second source"

Reactive Streams semantics

emits when an element is available from first stream or first stream closed without emitting any elements and an element is available from the second stream

backpressures when downstream backpressures

completes the primary stream completes after emitting at least one element, when the primary stream completes without emitting and the secondary stream already has completed or when the secondary stream completes