Skip to content

Commit

Permalink
新增 IAwait<T>.repeat 操作符,以支持轮训请求
Browse files Browse the repository at this point in the history
  • Loading branch information
liujingxing committed Jun 24, 2021
1 parent a89a705 commit 00605f5
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions rxhttp/src/main/java/rxhttp/IAwait.kt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,34 @@ fun <T> IAwait<T>.retry(
}
}

/**
* @param times repeat times, default Long.MAX_VALUE Always repeat
* @param period repeat period, default 0, time in milliseconds
* @param stop repeat stop conditions, default false,Unconditional repeat
*/
fun <T> IAwait<T>.repeat(
times: Long = Long.MAX_VALUE,
period: Long = 0,
stop: suspend (T) -> Boolean = { false }
): IAwait<T> = object : IAwait<T> {

var remaining = if (times == Long.MAX_VALUE) Long.MAX_VALUE else times - 1

override suspend fun await(): T {
while (remaining > 0) {
if (remaining != Long.MAX_VALUE) {
remaining--
}
val t = this@repeat.await()
if (stop(t)) {
return t
}
kotlinx.coroutines.delay(period)
}
return this@repeat.await()
}
}

/**
* Changes the context where this flow is executed to the given [context].
* This operator is composable and affects only preceding operators that do not have its own context.
Expand Down

0 comments on commit 00605f5

Please sign in to comment.