如何使用 RxJava 创建可重复的网络请求?

How to create repeatable network requests with RxJava?

我需要我的请求每 30 秒重复一次。如何在此代码中强制 repeatWhen?

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())
            })
            )
        }

您需要在 subscribeOn 之前添加此内容以重复相同的请求:

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

因此它会每隔 30 秒调用一次相同的请求。

因此您的代码变为:

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