Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating periodically with RxSwift

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.

like image 924
tilo Avatar asked Sep 06 '16 19:09

tilo


People also ask

What is RxSwift in iOS?

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.

Is RxSwift a framework?

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.

What is variable RxSwift?

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”.


2 Answers

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")
    // ...
like image 133
solidcell Avatar answered Nov 03 '22 23:11

solidcell


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)
    }
like image 37
Eluss Avatar answered Nov 04 '22 00:11

Eluss