Created
June 26, 2021 01:05
-
-
Save swhitty/9c47d2d52bbd4261ee588084a7486b43 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Combine | |
/// Subscriber that weakly references its target with a closure. | |
/// The target is sent to the action when it exists, so the caller can avoid | |
/// the [weak self] dance. | |
/// | |
/// ``` | |
/// let binder = Binder(self) { $0.doSomething($1) ) | |
/// ``` | |
/// | |
final class Binder<Input>: Subscriber { | |
private var handler: ((Input) -> Void)? | |
private var subscription: Subscription? | |
init<Target: AnyObject>(_ target: Target, action: @escaping (Target, Input) -> Void) { | |
handler = { [weak target] input in | |
if let target = target { | |
action(target, input) | |
} | |
} | |
} | |
func receive(subscription: Subscription) { | |
self.subscription = subscription | |
subscription.request(.unlimited) | |
} | |
func receive(_ input: Input) -> Subscribers.Demand { | |
handler!(input) | |
return .unlimited | |
} | |
func receive(completion _: Subscribers.Completion<Never>) { | |
subscription = nil | |
handler = nil | |
} | |
func cancel() { | |
subscription!.cancel() | |
subscription = nil | |
handler = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment