Created
December 31, 2023 00:25
-
-
Save mRB0/2cd7ffe7e1dc3ce17d903d213c6b9d92 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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