Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Repeating a suspend function / method

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}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading