Skip to content

Instantly share code, notes, and snippets.

@mRB0
Created December 31, 2023 00:25
Show Gist options
  • Save mRB0/2cd7ffe7e1dc3ce17d903d213c6b9d92 to your computer and use it in GitHub Desktop.
Save mRB0/2cd7ffe7e1dc3ce17d903d213c6b9d92 to your computer and use it in GitHub Desktop.
package org.example
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.Executors
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
fun processInteger(i: Int): String {
// blocks the whole thread! run it on IO dispatcher in a coroutine context
Thread.sleep(1000)
return "Done for $i"
}
suspend fun suspendProcessInteger(i: Int) = withContext(IO) {
processInteger(i)
}
fun main() {
val listOfThings = (1..10).toList()
val results = runBlocking {
val resultDeferreds = listOfThings.map {
//async(IO) { processInteger(it) }
async { suspendProcessInteger(it) }
}
resultDeferreds.awaitAll()
}
println(results)
}
// more functions!!
private val sharedExecutor = Executors.newCachedThreadPool()
fun processWithCallback(i: Int, callback: (str: String) -> Unit) {
sharedExecutor.submit {
val result = processInteger(i)
callback(result)
}
}
suspend fun suspendProcessWithCallback(i: Int): String {
return suspendCoroutine { continuation ->
processWithCallback(i) {
continuation.resume(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment