Created
November 15, 2016 15:04
-
-
Save darrensapalo/faf4307c84deaf0c05d02c17de7e118b to your computer and use it in GitHub Desktop.
Exiting the Rx Monad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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