Instance Method

prefix(while:)

Republishes elements while a predicate closure indicates publishing should continue.

Declaration

func prefix(while predicate: @escaping (Self.Output) -> Bool) -> Publishers.PrefixWhile<Self>

Parameters

predicate

A closure that takes an element as its parameter and returns a Boolean value indicating whether publishing should continue.

Return Value

A publisher that passes through elements until the predicate indicates publishing should finish.

Discussion

Use prefix(while:) to emit values while elements from the upstream publisher meet a condition you specify. The publisher finishes when the closure returns false.

In the example below, the prefix(while:) operator emits values while the element it receives is less than five:

let numbers = (0...10)
numbers.publisher
    .prefix { $0 < 5 }
    .sink { print("\($0)", terminator: " ") }

// Prints: "0 1 2 3 4"

See Also

Applying Sequence Operations to Elements

func drop<P>(untilOutputFrom: P) -> Publishers.DropUntilOutput<Self, P>

Ignores elements from the upstream publisher until it receives an element from a second publisher.

func dropFirst(Int) -> Publishers.Drop<Self>

Omits the specified number of elements before republishing subsequent elements.

func drop(while: (Self.Output) -> Bool) -> Publishers.DropWhile<Self>

Omits elements from the upstream publisher until a given closure returns false, before republishing all remaining elements.

func tryDrop(while: (Self.Output) -> Bool) -> Publishers.TryDropWhile<Self>

Omits elements from the upstream publisher until an error-throwing closure returns false, before republishing all remaining elements.

func append<S>(S) -> Publishers.Concatenate<Self, Publishers.Sequence<S, Self.Failure>>

Appends a publisher’s output with the specified sequence.

func append<P>(P) -> Publishers.Concatenate<Self, P>

Appends the output of this publisher with the elements emitted by the given publisher.

func prepend<S>(S) -> Publishers.Concatenate<Publishers.Sequence<S, Self.Failure>, Self>

Prefixes a publisher’s output with the specified sequence.

func prepend<P>(P) -> Publishers.Concatenate<P, Self>

Prefixes the output of this publisher with the elements emitted by the given publisher.

func prefix(Int) -> Publishers.Output<Self>

Republishes elements up to the specified maximum count.

func tryPrefix(while: (Self.Output) -> Bool) -> Publishers.TryPrefixWhile<Self>

Republishes elements while an error-throwing predicate closure indicates publishing should continue.

func prefix<P>(untilOutputFrom: P) -> Publishers.PrefixUntilOutput<Self, P>

Republishes elements until another publisher emits an element.