Skip to content

Instantly share code, notes, and snippets.

@0xLeif
Last active March 16, 2019 02:46
Show Gist options
  • Save 0xLeif/1d1700031701d581f8b9f3fcc7a677e5 to your computer and use it in GitHub Desktop.
Save 0xLeif/1d1700031701d581f8b9f3fcc7a677e5 to your computer and use it in GitHub Desktop.
RxSwift SubscribeIf
import UIKit
import RxSwift
class TFObservable<E> {
var disposable: Disposable
private var trueBlock: ((E) -> Void)?
private var falseBlock: ((E) -> Void)?
init() {
self.trueBlock = nil
self.falseBlock = nil
self.disposable = Observable.just(false).subscribe()
}
func onTrue(element: E) {
if let block = trueBlock {
block(element)
}
}
func onFalse(element: E) {
if let block = falseBlock {
block(element)
}
}
func `true`(_ block: @escaping (E) -> Void) -> TFObservable {
self.trueBlock = block
return self
}
func `false`(_ block: @escaping (E) -> Void) -> Disposable {
self.falseBlock = block
return disposable
}
func disposed(by bag: DisposeBag) {
disposable
.disposed(by: bag)
}
}
extension Observable {
func subscribeIf(_ block: @escaping (Element) -> Bool) -> TFObservable<Element> {
let tf = TFObservable<Element>()
tf.disposable = subscribe(onNext: { (element) in
block(element) ? tf.onTrue(element: element) : tf.onFalse(element: element)
})
return tf
}
}
class ViewController: UIViewController {
var subject = PublishSubject<String>()
var otherSubject = PublishSubject<Int>()
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
subject
.subscribeIf { (value) -> Bool in
return value == "Hello World"
}
.true { (value) in
print("True: \(value)")
}
.false { (value) in
print("False: \(value)")
}
.disposed(by: disposeBag)
otherSubject
.subscribeIf { $0 == 5423 }
.true { print("value: \($0) == 5423") }
.disposed(by: disposeBag)
// On Next
otherSubject.onNext(123)
otherSubject.onNext(5423)
subject.onNext("Hello")
subject.onNext("Hello World")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment