Skip to content

Commit

Permalink
Improve EventAsk + timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
Alkenso committed Aug 29, 2024
1 parent e50e763 commit 6350f64
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions Sources/SpellbookFoundation/ValueObserving/EventAsk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,19 +108,15 @@ public class EventAskEx<Input, Transformed, Output> {
if let timeout {
queue.asyncAfter(delay: timeout.interval) {
guard !once.testAndSet() else { return }
timeout.onTimeout?()
completion(values.get(fallback: timeout.fallback, combine: self.combine))
completion(values.get(fallback: timeout.onTimeout(), combine: self.combine))
}
}
}

@inline(__always)
private func waitSync(on group: DispatchGroup, with values: Values, timeout: Timeout?) -> Output {
let waitSucceeds = group.wait(interval: timeout?.interval) == .success
if !waitSucceeds {
timeout?.onTimeout?()
}
return values.get(fallback: waitSucceeds ? nil : timeout?.fallback, combine: combine)
return values.get(fallback: waitSucceeds ? nil : timeout?.onTimeout(), combine: combine)
}

// MARK: Subscribe
Expand Down Expand Up @@ -155,13 +151,16 @@ public class EventAskEx<Input, Transformed, Output> {
extension EventAskEx {
public struct Timeout {
public var interval: TimeInterval
public var fallback: Fallback?
public var onTimeout: (() -> Void)?
public var onTimeout: () -> Fallback? = { nil }

public init(_ interval: TimeInterval, fallback: Fallback? = nil) {
public init(_ interval: TimeInterval, onTimeout: @escaping () -> Fallback? = { nil }) {
self.interval = interval
self.fallback = fallback
self.onTimeout = onTimeout
}

public init(_ interval: TimeInterval, fallback: Fallback?) {
self.init(interval) { fallback }
}
}

public enum Fallback {
Expand Down

0 comments on commit 6350f64

Please sign in to comment.