From 1c6c4da637a9bd1e98e85b065acec6ab399d3ece Mon Sep 17 00:00:00 2001 From: Erik Terwan Date: Mon, 28 Mar 2022 16:23:34 +0200 Subject: [PATCH] Add `sink` method to quickly attach a MMMLoadableObserver So it now passes the actual loadable subclass instead of a generic MMMPureLoadableProtocol inside the closure. --- MMMLoadable.podspec | 2 +- Sources/MMMLoadable/MMMLoadable.swift | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/MMMLoadable.podspec b/MMMLoadable.podspec index 8f9bc67..109a981 100644 --- a/MMMLoadable.podspec +++ b/MMMLoadable.podspec @@ -6,7 +6,7 @@ Pod::Spec.new do |s| s.name = "MMMLoadable" - s.version = "1.6.4" + s.version = "1.7.0" s.summary = "A simple model for async calculations" s.description = "#{s.summary}." s.homepage = "https://github.com/mediamonks/#{s.name}" diff --git a/Sources/MMMLoadable/MMMLoadable.swift b/Sources/MMMLoadable/MMMLoadable.swift index f04a00c..e35fedd 100644 --- a/Sources/MMMLoadable/MMMLoadable.swift +++ b/Sources/MMMLoadable/MMMLoadable.swift @@ -13,3 +13,18 @@ extension MMMLoadableState: CustomDebugStringConvertible { public var debugDescription: String { NSStringFromMMMLoadableState(self) } } + +extension MMMPureLoadableProtocol { + + /// Observe changes in this loadable. Will stop listening to changes when + /// ``MMMLoadableObserver/remove()`` is called or the observer deallocates. + /// + /// - Parameter block: Get's called every time the loadable changes. + /// - 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: @escaping (Self) -> Void) -> MMMLoadableObserver? { + return MMMLoadableObserver(loadable: self) { loadable in + block(loadable as! Self) + } + } +}