let publisher = CurrentValueSubject<String, Never>("")
let label = UILabel()
let binder = CombineBinder<String>(label) { label, str in
label.text = str
}
publisher
.bind(to: binder)
.store(in: &bag)
Last active
May 4, 2023 10:10
-
-
Save woodycatliu/fb5a9fc36f8586271e7ea0dc781f2ac2 to your computer and use it in GitHub Desktop.
Combine Cocoa: CombineBinder
This file contains 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 | |
extension Publisher where Failure == Never { | |
public func bind(to binder: CombineBinder<Output>) -> AnyCancellable { | |
subscribe(binder) | |
return AnyCancellable(binder) | |
} | |
public func handleEvents(to binder: CombineBinder<Output>) -> Publishers.HandleEvents<Self> { | |
return handleEvents(receiveOutput: binder.binding) | |
} | |
} | |
public struct CombineBinder<Input>: Subscriber, Cancellable { | |
public typealias Failure = Never | |
public init<Target: AnyObject, Scheduler: Combine.Scheduler>(_ target: Target, | |
scheduler: Scheduler = DispatchQueue.main, | |
binding: @escaping (Target, Input) -> Void) { | |
self._bind = { [weak target] input in | |
scheduler.schedule { [weak target] in | |
if let target = target { | |
binding(target, input) | |
} | |
} | |
} | |
} | |
public func receive(_ input: Input) -> Subscribers.Demand { | |
self._bind(input) | |
return .unlimited | |
} | |
public func receive(subscription: Subscription) { | |
self.subscontainter.subscription = subscription | |
subscription.request(.unlimited) | |
} | |
public var combineIdentifier: CombineIdentifier { | |
return CombineIdentifier() | |
} | |
public func cancel() { | |
subscontainter.subscription?.cancel() | |
} | |
fileprivate var binding: (Input) -> () { | |
return _bind | |
} | |
private let _bind: (Input) -> Void | |
public func receive(completion: Subscribers.Completion<Failure>) {} | |
private let subscontainter = SubscriptionContainer() | |
private class SubscriptionContainer { | |
var subscription: Subscription? | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment