Instance Method

tryPrefix(while:)

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

Declaration

func tryPrefix(while predicate: @escaping (Self.Output) throws -> Bool) -> Publishers.TryPrefixWhile<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 throws or indicates publishing should finish.

Discussion

Use tryPrefix(while:) to emit values from the upstream publisher that meet a condition you specify in an error-throwing closure. The publisher finishes when the closure returns false. If the closure throws an error, the publisher fails with that error.

struct OutOfRangeError: Error {}

let numbers = (0...10).reversed()
cancellable = numbers.publisher
    .tryPrefix {
        guard $0 != 0 else {throw OutOfRangeError()}
        return $0 <= numbers.max()!
    }
    .sink(
        receiveCompletion: { print ("completion: \($0)", terminator: " ") },
        receiveValue: { print ("\($0)", terminator: " ") }
    )
          
// Prints: "10 9 8 7 6 5 4 3 2 1 completion: failure(OutOfRangeError()) "

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 prefix(while: (Self.Output) -> Bool) -> Publishers.PrefixWhile<Self>

Republishes elements while a predicate closure indicates publishing should continue.

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

Republishes elements until another publisher emits an element.