-
-
Save marksands/28bdd30c8b2dab533cd98e21c3a71a99 to your computer and use it in GitHub Desktop.
RxSwift subject to provide public triggering but private subscription
This file contains hidden or 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
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