How can I repeat a suspend function after a 10 seconds delay?
Code
suspend fun ethPriceRequestFun(): Double { ... here is the code }
fun callRequest() = runBlocking { running the ethPriceRequestFun function}
CodePudding user response:
fun main(args: Array<String>) {
callRequest()
}
Here ethPriceRequestFun
is suspend function which runs computed value with small delay.
suspend fun ethPriceRequestFun(int: Int): Int {
delay(10)
return int*20
}
From callRequest
function you are calling ethPriceRequestFun
repeatedly with delay of one second.
fun callRequest() = runBlocking{
repeat(5) {
delay(1.toDuration(DurationUnit.SECONDS))
println(ethPriceRequestFun(it))
}
}
Here the output will be like this.
0 20 40 60 80
Here repeat is a loop which runs 5 times. So indices will be (0,1,2,3,4).
In ethPriceRequestFun
we multiple the value by 20 and print.
These numbers will be printed with one second delay after each.
Make sure to import this.
import kotlin.time.toDuration
Hope it helps.