Engineering

Introduce filterLatestFrom in RxSwift 4.0

Filter is good operator

Filter of ReactiveProgramming is good operator. But, If you want evaluate with other Observable or Variable, you may write lenghty code.

For example

let source = PublishSubject<Void>()
let isEnabled = Variable(false)

source
  .filter {
    isEnabled.value == true
}

If isEnabled is stored property.

source
  .filter { [weak self] in
    guard let `self` = self else {
      return false // really?
    }
    return self.isEnabled.value == true
}

This is not good code.
So, I've created following snippet code.

filterLatestFrom

extension ObservableType {

  public func filterLatestFrom<S: ObservableConvertibleType>(_ second: S, _ predicate: @escaping (S.E) -> Bool) -> Observable<Self.E> {

    return withLatestFrom(second) { s, e -> Observable<Self.E> in
      if predicate(e) {
        return Observable<Self.E>.just(s)
      }
      return Observable<Self.E>.empty()
      }
      .merge()
  }
}

Usage

let source = PublishSubject<Void>()
let isEnabled = Variable(false)

source
  .filterLatestFrom(isEnabled.asObservable()) { $0 == true }
  .do(onNext: {
    // Through only isEnabled is true
  })

Is not this great?