5

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.

tilo
  • 14,009
  • 6
  • 68
  • 85

2 Answers2

13

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")
    // ...
Community
  • 1
  • 1
solidcell
  • 7,639
  • 4
  • 40
  • 59
3

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)
    }
Eluss
  • 512
  • 3
  • 5