RxSwift Binder

  • 内容
  • 评论
  • 相关

我们想绑定一个UIViewController的titile,我们可以这样写

ViewModel 文件

self.title = Observable.create{ observer -> Disposable in
observer.onNext((parentModel.name_c) ?? "生物树🌲")
return Disposables.create()
}

Controller文件

        output.title.subscribe(onNext :{title in
            self.title = title
            })
            .disposed(by: disposeBag)

或者
        let observer: AnyObserver<String> = AnyObserver { [weak self] (event) in
            switch event {
            case .next(let title):
                self?.title = title
            default:
                break
            }
        }
        
        output.title.bind(to: observer).disposed(by: disposeBag)

但是这样不是很优雅甚至有点傻,所以我们可以用Binder

        let observer2: Binder<String> = Binder(self) { (viewController, title) in
            viewController.title = title
        }
        
        output.title.bind(to: observer2).disposed(by: disposeBag);

封装下

extension Reactive where Base:UIViewController
{
    public var title : Binder<String>
    {
        return Binder(self.base) { (viewController, title) in
            viewController.title = title
        }
    }
}

使用
        output.title.bind(to: self.rx.title).disposed(by: disposeBag)

评论

0条评论

发表评论

电子邮件地址不会被公开。