Skip to content

Instantly share code, notes, and snippets.

@NielsMasdorp
Created September 26, 2018 13:36
Show Gist options
  • Save NielsMasdorp/d645a8815cd833eec7d5e7ea2775c03d to your computer and use it in GitHub Desktop.
Save NielsMasdorp/d645a8815cd833eec7d5e7ea2775c03d to your computer and use it in GitHub Desktop.
RxJava2: Have an action (like a loading spinner) be invoked when an observable takes a long time and not instantaneously
/**
 * Invoke some action when the observable does not emit an item for longer than a given time out
 * @param timeout time out
 * @param timeUnit the unit for the time out
 * @param scheduler the scheduler on which the action must be ran
 * @param action the action to invoke
 */
fun <T> Observable<T>.startAfterDelay(timeout: Long, timeUnit: TimeUnit, scheduler: Scheduler, action: () -> Unit): Observable<T> {
    return this.publish { o ->
        o.timeout(timeout, timeUnit, scheduler) {
            action.invoke()
        }.mergeWith(o)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment