Skip to content

Commit

Permalink
Use weak self reference in .sink instead of force casting
Browse files Browse the repository at this point in the history
  • Loading branch information
terwanerik committed Mar 29, 2022
1 parent 3e39dd1 commit 9636c9f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
3 changes: 2 additions & 1 deletion MMMAsyncLoadable.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
Pod::Spec.new do |s|

s.name = "MMMAsyncLoadable"
s.version = "0.3.0"
s.version = "0.3.1"
s.summary = "Use async/await with MMMLoadable"
s.description = s.summary
s.homepage = "https://github.com/mediamonks/#{s.name}"
Expand All @@ -26,4 +26,5 @@ Pod::Spec.new do |s|
}
s.source_files = [ "Sources/#{s.name}/*.swift" ]
s.dependency "MMMLoadable"
s.dependency "MMMCommonCore"
end
5 changes: 3 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ let package = Package(
)
],
dependencies: [
.package(name: "MMMLoadable", url: "https://github.com/mediamonks/MMMLoadable", .upToNextMajor(from: "1.7.0"))
.package(name: "MMMLoadable", url: "https://github.com/mediamonks/MMMLoadable", .upToNextMajor(from: "1.7.0")),
.package(name: "MMMCommonCore", url: "https://github.com/mediamonks/MMMCommonCore", .upToNextMajor(from: "1.8.2"))
],
targets: [
.target(
name: "MMMAsyncLoadable",
dependencies: ["MMMLoadable"]
dependencies: ["MMMLoadable", "MMMCommonCore"]
),
.testTarget(
name: "MMMAsyncLoadableTests",
Expand Down
9 changes: 7 additions & 2 deletions Sources/MMMAsyncLoadable/AsyncLoadableObserver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import Foundation
import MMMLoadable
import MMMCommonCore

/// ``MMMLoadableObserver`` that supports asynchronous closures as it's callback.
public final class AsyncLoadableObserver: MMMLoadableObserver {
Expand All @@ -31,8 +32,12 @@ extension MMMPureLoadableProtocol {
/// - Returns: The observer, you usually want to store this outside of the scope, e.g.
/// in a private property so it doesn't deallocate right away.
public func sink(_ block: @Sendable @escaping (Self) async -> Void) -> AsyncLoadableObserver? {
return AsyncLoadableObserver(loadable: self) { loadable in
await block(loadable as! Self)
return AsyncLoadableObserver(loadable: self) { [weak self] loadable in
guard let self = self else {
assertionFailure("\(MMMTypeName(Self.self)) was lost inside the observer callback?")
return
}
await block(self)
}
}
}

0 comments on commit 9636c9f

Please sign in to comment.