Search code examples
androidkotlinrx-java2

How to create repeatable network requests with RxJava?


I need my request to repeat once every 30 seconds. How can I force repeatWhen in this code?

override fun loadData() {
    disposable.add(
        weatherRepository.getCurrentLocation(activity)
            .flatMap { weatherRepository.getWeather(it.currentLocation).subscribeOn(Schedulers.io()) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                mView.showWeather()
                mView.setupWeather(it)
            }, {
                checkNetworkConnection()
                Log.d("Error", it.toString())
            })
            )
        }

Solution

  • You need to add this before subscribeOn to repeat the same request:

    .repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }
    

    So it will call the same request every 30 seconds of interval.

    So your code becomes:

    disposable.add(weatherRepository.getCurrentLocation(activity)
                .flatMap { weatherRepository.getWeather(it.currentLocation)
                .repeatWhen { completed -> completed.delay(30, TimeUnit.SECONDS) }
                .subscribeOn(Schedulers.io()) }
        ....