With RxSwift, it can support bind to a function/closure to more readability.
Example
textField.rx.text.orEmpty.asObservable()
.subscribeOn(MainScheduler.instance)
.bind(onNext: receiveText(_:))
.disposed(by: disBag)
With Combine in Swift, there is a operator assign for support bindding is achieved by KeyPath(ReferenceWritableKeyPath). ReferenceWritableKeyPath doest not support the function. But We still can use Closure Type to make this.
Code
public func assign(to action: @escaping ((Output)->()))-> AnyCancellable {
sink(receiveCompletion: { _ in } , receiveValue: {
action($0)
})
}
Example
textField.textPublisher()
.map { Optional($0) }
.receive(on: DispatchQueue.main)
.assign(to: changeText(_:))
.store(in: &bag)
Now I can use it like this, but I found it is not perfect.
There are some potential crisis, like retain cycle.
So how can I do.......
In order to prevent from retaining cycle, I specify the action been Instace Method, and change paramaters to Method Type and Instance. There are not any potential crisis with Retain Cycle to make new version . "
public func assign<T: AnyObject>(to action: @escaping ((T)->(Output)->()), on target: T)-> AnyCancellable {
return sink(receiveCompletion: { _ in } , receiveValue: {
[weak target] in
guard let target = target else { return }
action(target)($0)
})
}
Use For
textField.textPublisher()
.map { Optional($0) }
.receive(on: DispatchQueue.main)
.assign(to: NewViewController.changeText, on: self)
.store(in: &bag)