<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Combine",
  "identifier" : "/documentation/Combine/Publisher/tryPrefix(while:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Combine"
    ],
    "preciseIdentifier" : "s:7Combine9PublisherPAAE9tryPrefix5whileAA10PublishersO03TryD5WhileVy_xGSb6OutputQzKc_tF"
  },
  "title" : "tryPrefix(while:)"
}
-->

# tryPrefix(while:)

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

```
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:)`](/documentation/Combine/Publisher/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()) "
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)