|
1 | 1 | //
|
2 |
| -// Publisher+RetryWhenDoBefore.swift |
| 2 | +// Publisher+RetryOnceIfDoBefore.swift |
3 | 3 | //
|
4 | 4 | //
|
5 | 5 | // Created by Andreas Osberghaus on 2023-02-27.
|
|
8 | 8 | import Foundation
|
9 | 9 | import Combine
|
10 | 10 |
|
11 |
| -extension Publisher { |
12 |
| - func retryOnly<Upstream: Publisher>( |
13 |
| - upstream: Upstream, |
14 |
| - retries: Int, |
15 |
| - when predicate: @escaping (Upstream.Failure) -> Bool, |
16 |
| - doBefore handler: () -> Void |
17 |
| - ) -> AnyPublisher<Upstream.Output, Upstream.Failure> { |
| 11 | +extension Publishers { |
| 12 | + struct RetryOnceIf<P: Publisher>: Publisher { |
| 13 | + typealias Output = P.Output |
| 14 | + typealias Failure = P.Failure |
| 15 | + |
| 16 | + let publisher: P |
| 17 | + let times: Int |
| 18 | + let condition: (P.Failure) -> Bool |
| 19 | + let doBefore: () -> Void |
18 | 20 |
|
19 |
| - upstream |
20 |
| - .map { output -> Result<Upstream.Output, Upstream.Failure> in .success(output) } |
21 |
| - .catch { error -> AnyPublisher<Result<Upstream.Output, Upstream.Failure>, Upstream.Failure> in |
22 |
| - if predicate(error) { |
23 |
| - return Fail(error: error).eraseToAnyPublisher() |
24 |
| - } else { |
25 |
| - return Just(.failure(error)) |
26 |
| - .setFailureType(to: Upstream.Failure.self) |
27 |
| - .eraseToAnyPublisher() |
| 21 | + func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { |
| 22 | + guard times > 0 else { |
| 23 | + return publisher.receive(subscriber: subscriber) |
28 | 24 | }
|
29 |
| - } |
30 |
| - .retry(retries) |
31 |
| - .flatMap { result in result.publisher } |
32 |
| - .eraseToAnyPublisher() |
33 |
| - } |
34 | 25 |
|
35 |
| - func retry(_ retries: Int, when predicate: @escaping (Failure) -> Bool, doBefore handler: () -> Void) -> AnyPublisher<Output, Failure> { |
36 |
| - return retryOnly(upstream: self, retries: retries, when: predicate, doBefore: handler) |
37 |
| - } |
| 26 | + publisher.catch { (error: P.Failure) -> AnyPublisher<Output, Failure> in |
| 27 | + if condition(error) { |
| 28 | + doBefore() |
| 29 | + return RetryOnceIf( |
| 30 | + publisher: publisher, |
| 31 | + times: times - 1, |
| 32 | + condition: condition, |
| 33 | + doBefore: doBefore |
| 34 | + ).eraseToAnyPublisher() |
| 35 | + } else { |
| 36 | + return Fail(error: error).eraseToAnyPublisher() |
| 37 | + } |
| 38 | + }.receive(subscriber: subscriber) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +extension Publisher { |
| 44 | + func retryOnce(if condition: @escaping (Failure) -> Bool, doBefore: @escaping () -> Void) -> Publishers.RetryOnceIf<Self> { |
| 45 | + Publishers.RetryOnceIf(publisher: self, times: 1, condition: condition, doBefore: doBefore) |
| 46 | + } |
38 | 47 | }
|
0 commit comments