Skip to content

Instantly share code, notes, and snippets.

@darrensapalo
Created November 15, 2016 15:04
Show Gist options
  • Save darrensapalo/faf4307c84deaf0c05d02c17de7e118b to your computer and use it in GitHub Desktop.
Save darrensapalo/faf4307c84deaf0c05d02c17de7e118b to your computer and use it in GitHub Desktop.
Exiting the Rx Monad
import RxSwift
protocol DeviceConnectionProtocol {
var id : Observable<String> { get }
}
class Person : DeviceConnectionProtocol {
var myName: String! = nil
init(name: String) {
self.myName = name
}
var id: Observable<String> {
return Observable.create { [unowned self] obx in
obx.onNext(self.myName)
return Disposables.create()
}
}
}
let rx_DeviceList = Variable([DeviceConnectionProtocol]())
let disposeBag = DisposeBag()
let lastID = "Hillary"
func lastDeviceSelected(device: DeviceConnectionProtocol) {
if let person = device as? Person {
print(person.myName + " was found!")
}
}
let devices = rx_DeviceList
.asObservable()
.flatMap { array in Observable.from(array) }
let deviceIDs = devices
.flatMap { device in device.id }
Observable.zip(devices, deviceIDs) { $0 }
.filter { $0.1 == lastID }
.map { $0.0 }
.subscribe(onNext: lastDeviceSelected)
rx_DeviceList.value = [Person(name: "Donald"), Person(name: "Goofy"), Person(name: "Hillary")]
// Output:
// Hilary was found!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment