Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Last active May 4, 2023 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodycatliu/fb5a9fc36f8586271e7ea0dc781f2ac2 to your computer and use it in GitHub Desktop.
Save woodycatliu/fb5a9fc36f8586271e7ea0dc781f2ac2 to your computer and use it in GitHub Desktop.
Combine Cocoa: CombineBinder

Use Combine like RxSwift

CombineBinder

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)

Enjoy it

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