Skip to content

Instantly share code, notes, and snippets.

@marksands
Forked from IanKeen/Driver+Create.swift
Created January 9, 2018 01:24
Show Gist options
  • Save marksands/28bdd30c8b2dab533cd98e21c3a71a99 to your computer and use it in GitHub Desktop.
Save marksands/28bdd30c8b2dab533cd98e21c3a71a99 to your computer and use it in GitHub Desktop.
RxSwift subject to provide public triggering but private subscription
class API {
func obtainIds() -> Observable<[Int]> {
return .just([1,2,3,4])
}
}
class ViewModel {
let update: AnyObserver<Void>
let dataUpdated: Observable<[String]>
init(api: API) {
//
// here is where we create the input/output
let subject = PublishSubject<Void>()
//
//
self.update = subject.asObserver()
self.dataUpdated = subject.asObservable()
.flatMap {
return api
.obtainIds()
.catchErrorJustReturn([])
}
.map { $0.flatMap(String.init) }
}
}
// in your view controllers data binding..
let viewModel = ViewModel(api: API())
// perhaps bind to a tableview
viewModel.dataUpdated.subscribe { e in
print(e)
}
// button triggers the input
someButton.rx.tap.bind(to: viewModel.update)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment