I use the following setup to retrieve objects (e.g. GitHub issues) from an API. This works fine.
let provider: RxMoyaProvider<GitHub>
let issues: Driver<[IssueViewModel]>
init(provider: RxMoyaProvider<GitHub>) {
self.provider = provider
issues = provider.request(.Issue)
.mapArray(Issue.self, keyPath: "issues")
.asDriver(onErrorJustReturn: [])
.map { (models: [Issue]) -> [IssueViewModel] in
let items = models.map {
IssueViewModel(name: $0.name,
description: $0.description
)
}
return items
}
}
Now I'd like to periodically update the list of issues (e.g., every 20 seconds). I thought about an NSTimer
to accomplish this task, but I guess there might be a clean(er) solution (i.e. in a Rx manner) that I didn't think about.
Any hint in the right direction is highly appreciated.
RxSwift is a library for composing asynchronous and event-based code by using observable sequences and functional style operators, allowing for parameterized execution via schedulers.
RxSwift is a framework for interacting with the swift programming language, while RxCocoa is a framework that makes cocoa APIs used in iOS and OS X easier to use with reactive techniques.
Variable is a concept added into RxSwift in its early days which basically let you create an imperative bridge by “setting” and “getting” a current value to and from it. It was a seemingly helpful measure to get developers started with RxSwift until they fully understand “Reactive Thinking”.
This is very similar to this question/answer.
You should use timer
and then flatMapLatest
:
Observable<Int>.timer(0, period: 20, scheduler: MainScheduler.instance)
.flatMapLatest { _ in
provider.request(.Issue)
}
.mapArray(Issue.self, keyPath: "issues")
// ...
You are probably looking for interval
operator.
Here is a loop example for interval
that will keep printing "test" every second.
Link to documentation: http://reactivex.io/documentation/operators/interval.html
var driver: Driver<String> {
return Driver<Int>.interval(1.0).map { _ in
return "test"
}
}
driver.asObservable().subscribeNext { (variable) in
print(variable)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With