Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active December 2, 2022 03:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/1a70c4f7b8960d06bd7f1bfa81802cc3 to your computer and use it in GitHub Desktop.
Save danielt1263/1a70c4f7b8960d06bd7f1bfa81802cc3 to your computer and use it in GitHub Desktop.
//
// Filter.swift
//
// Created by Daniel Tartaglia on 8/25/2018.
// Copyright © 2019 Daniel Tartaglia. MIT License.
//
import RxSwift
extension ObservableType {
/// Filters the source observable sequence using a trigger observable sequence producing Bool values.
/// Elements only go through the filter when the trigger has not completed and
/// its last element was true. If either source or trigger error's, then the source errors.
///
/// - Parameter trigger: Triggering event sequence.
/// - Returns: Filtered observable sequence.
func filter<O>(if trigger: O) -> Observable<Element> where O: ObservableType, O.Element == Bool {
return self.withLatestFrom(trigger) { ($0, $1) }
.filter { $0.1 }
.map { $0.0 }
}
/// Filters the source observable sequence using a trigger observable sequence.
/// Elements only go through the filter when the trigger has not completed and
/// its last element produces a true value from the pred. If either source or trigger error's, then the source errors.
///
/// - Parameters:
/// - trigger: The sequence to compare with.
/// - pred: The predicate function to determine if the element should pass through.
/// - Returns: An Observable of the same type that passed the filter test.
func filter<O>(if trigger: O, _ pred: @escaping (Element, O.Element) -> Bool) -> Observable<Element> where O: ObservableType {
return self.withLatestFrom(trigger) { ($0, $1) }
.filter { pred($0.0, $0.1) }
.map { $0.0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment