有没有办法让Observable.bind和诸如fold之类的东西合拢?

时间:2019-02-05 16:22:40

标签: ios swift rx-swift

所以我想知道在使用RxSwift编写viewModel时是否有一种结合绑定和折叠的方法,以便您获得像这样的签名

someObservable.bind(someCondition, firstObserver,secondObserver)

它将是替换代码,例如

someObservable
    .filter { continionIsTrue }
    .bind(to: firstObserver)
    .disposed(by: disposeBag)

someObservable
    .filter { conditionIsFalse }
    .bind(to: secondObserver)
    .disposed(by: disposeBag)

1 个答案:

答案 0 :(得分:0)

也许遵循以下原则:

extension ObservableType {
    func bindCondition<T, U>(_ predicate: @escaping (E) throws -> Bool, ifTrue: T, ifFalse: U) -> Disposable where T: ObserverType, U: ObserverType, T.E == E, U.E == E {
        return Disposables.create([
            filter(predicate).bind(to: ifTrue),
            filter { try !predicate($0) }.bind(to: ifFalse)
        ])
    }
}