[英]RxJava only emit item if another source will not item for some period
[英]RxJava emit item with minimum delay
我有要在啟動屏幕期間下載的UserConfig
。
class UserManager {
Single<UserConfig> loadConfig()
}
下載UserConfig
,用戶將重定向到下一個屏幕。 我做這樣的事情:
@Override
public void onResume(boolean isNewView) {
subscriptions.add(
userManager.loadConfig().subscribe(config -> {
applyConfig(config);
launchActivity(HomeActivity.class);
}, error -> {
//some error handling
})
);
}
但是,我想顯示啟動屏幕至少1秒鍾 。 (如果加載時間少於1秒,則會增加額外的延遲)
我認為.delay()
.delaySubscription()
不適用於我的情況,因為它們會延遲每個請求(無論是否短於1s)。
嘗試Zip運算符
返回一個Single,它發出指定組合器函數的結果>應用於其他兩個Singles發出的兩個項目。
你可以做類似的事情
Single
.zip(
Single.timer(1, TimeUnit.SECONDS),
userManager.loadConfig(),
(time, config) -> config
)
.subscribe(
config -> {
applyConfig(config);
launchActivity(HomeActivity.class);
}, error -> {
//some error handling
}
);
我的解決方案具有針對單類型的kotlin擴展功能。 這種延遲與錯誤類似
/**
* sets the minimum delay on the success or error
*/
fun <T> Single<T>.minDelay(time: Long, unit: TimeUnit, scheduler: Scheduler = Schedulers.computation()): Single<T> {
val timeStart = scheduler.now(TimeUnit.MILLISECONDS)
val delayInMillis = TimeUnit.MILLISECONDS.convert(time, unit)
return Single.zip(
Single.timer(time, unit, scheduler),
this.onErrorResumeNext { error: Throwable ->
val afterError = scheduler.now(TimeUnit.MILLISECONDS)
val millisPassed = afterError - timeStart
val needWaitDelay = delayInMillis - millisPassed
if (needWaitDelay > 0)
Single.error<T>(error)
.delay(needWaitDelay, TimeUnit.MILLISECONDS, scheduler, true)
else
Single.error<T>(error)
},
BiFunction { _, t2 -> t2 }
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.