RxSwift - How to call method which returns Driver at regular intervals?

623 views Asked by At

I am a RxSwift beginner and making a app with RxSwift + MVVM.

I have a method which calls API and converts to RxCocoa.Driver in ViewModel class like below.

    func fetch() -> Driver<HomeViewEntity> {
        apiUseCase.fetch(query: HomeViewQuery())
            .map { data in
                HomeViewEntity(userName: data.name,
                               emailAddress: data.email
            }
            .asDriver(onErrorRecover: { [weak self] error in
                if let printableError = error as? PrintableError {
                    self?.errorMessageRelay.accept(AlertPayload(title: printableError.title, message: printableError.message))
                }

                return Driver.never()
            })

    }

Now, I'd like to call this fetchListPlace() method at regular intervals a.k.a polling (e.g. each 5 minutes) at ViewController.

How to do that????

I think interval is suit in this case, but I can't get an implementation image....

1

There are 1 answers

0
Daniel T. On

Here you go:

func example(_ fetcher: Fetcher) -> Driver<HomeViewEntity> {
    Driver<Int>.interval(.seconds(5 * 60))
        .flatMap { _ in fetcher.fetch() }
}

Also note,

  • Returning a Driver.never() from your recovery closure is probably a bad idea. Prefer Driver.empty() instead.
  • I'm not a fan of putting a side effect in the recovery closure in the first place. I think it would be better to have the fetch() return a Driver<Result<HomeViewEntity, Error>> instead and move the side effect to the end of the chain (in a subscribe or a flatMap.)