Skip to content

Instantly share code, notes, and snippets.

@vashisthg
Last active March 14, 2019 21:13
Show Gist options
  • Save vashisthg/f91e0093eaaec8a7d123b0d2a6f9300f to your computer and use it in GitHub Desktop.
Save vashisthg/f91e0093eaaec8a7d123b0d2a6f9300f to your computer and use it in GitHub Desktop.
Trying coroutine. Kind of debounce.
import kotlinx.coroutines.*
/*
* Trying learning couroutine. Investigating for getting debounce effect.
* Some inspiration from https://medium.com/@pro100svitlo/edittext-debounce-with-kotlin-coroutines-fd134d54f4e9
*/
fun main() {
val list = listOf(1, 2, 3, 4, 5)
var time = java.util.Calendar.getInstance().timeInMillis
for (i in list) {
Thread.sleep(15) // block main thread for 15 milli seconds
var timeNow = java.util.Calendar.getInstance().timeInMillis
if (timeNow == time) {
return
}
time = timeNow
GlobalScope.launch { // launch new coroutine in background and continue
delay(300) // non-blocking delay for 300 milli second (default time unit is ms)
if (time != timeNow) {
return@launch
}
println("World! $i") // print
}
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(5000L) // block main thread for 5 seconds to keep JVM alive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment