Search code examples
iosswiftrx-swift

Is there a way to convine Observable.bind and something like fold?


So I was wondering while writing a viewModel using RxSwift if there is a way to combine bind and fold so you a signature like this

someObservable.bind(someCondition, firstObserver,secondObserver)

it will be replace code like

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

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

Solution

  • Perhaps something along these lines:

    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)
            ])
        }
    }