Skip to content

Commit

Permalink
MMMLoadable: add async/await helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
aleh committed Jan 23, 2024
1 parent b4a5bed commit 73cc44e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
8 changes: 4 additions & 4 deletions MMMLoadable.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
Pod::Spec.new do |s|

s.name = "MMMLoadable"
s.version = "2.0.0"
s.version = "2.1.0"
s.summary = "A simple model for async calculations"
s.description = "#{s.summary}."
s.homepage = "https://github.com/mediamonks/#{s.name}"
s.license = "MIT"
s.authors = "MediaMonks"
s.source = { :git => "https://github.com/mediamonks/#{s.name}.git", :tag => s.version.to_s }

s.ios.deployment_target = '11.0'
s.watchos.deployment_target = '3.0'
s.tvos.deployment_target = '10.0'
s.ios.deployment_target = '14.0'
s.watchos.deployment_target = '6.0'
s.tvos.deployment_target = '13.0'

s.subspec 'ObjC' do |ss|
ss.source_files = [ "Sources/#{s.name}ObjC/*.{h,m}" ]
Expand Down
28 changes: 28 additions & 0 deletions Sources/MMMLoadable/MMMLoadable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,34 @@ extension MMMPureLoadableProtocol {
block(self)
}
}

/// Waits for the receiver to stop syncing and continues if `isContentsAvailable`; throws otherwise.
public func doneSyncing() async throws {
try await contentsAfterDoneSyncing { _ in }
}

/// Waits for the receiver to stop syncing; then, if `isContentsAvailable`, returns the result of the given closure;
/// throws otherwise.
public func contentsAfterDoneSyncing<T>(_ grabContents: @escaping (Self) throws -> T) async throws -> T {
try await withCheckedThrowingContinuation { continuation in
DispatchQueue.main.async {
var waiter: MMMSimpleLoadableWaiter?
waiter = MMMSimpleLoadableWaiter.whenDoneSyncing(self) {
do {
if self.isContentsAvailable {
continuation.resume(returning: try grabContents(self))
} else {
throw self.error ?? NSError(domain: self, message: "Unspecified error")
}
} catch {
continuation.resume(throwing: error)
}
// We need to keep the waiter around while waiting.
_ = waiter
}
}
}
}
}

/// Forwards all calls in `MMMPureLoadableProtocol` to another object.
Expand Down

0 comments on commit 73cc44e

Please sign in to comment.