谢谢你的有趣情节。这里有一个解决方案,我相信可以满足您的需求。它比您的解决方案长,但在涉及多个订阅时应该是安全的。
// subscribe to this observable with one or more subscribers
val requestObservable = replayAndRetry(API.request(), defaultObject)
private fun <T> replayAndRetry(request: Single<T>, defaultValue: T): Observable<T> {
val responses = BehaviorSubject.create<T>()
val initialRequest = request
.onErrorReturnItem(defaultValue)
.doOnSuccess(responses::onNext)
.ignoreElement()
.cache() // run the initial request at most once
val retryWhenNecessary = Maybe
.fromCallable { if (responses.value == defaultValue) true else null }
.flatMapCompletable { request
.doOnSuccess(responses::onNext)
.ignoreElement()
.onErrorComplete() // subject already has the default value
}
.toObservable<T>().share() // avoid multiple simultaneous retries
return responses // source for all responses
.mergeWith(initialRequest) // will run once and then complete
.mergeWith(retryWhenNecessary) // will check for default item on every subscription
// will not run simultaneous retries
}