이 글은 Asynchronous Flow(비동기 처리)를 다루지 않습니다.
val job = GlobalScope.launch(Dispatchers.Default)
{
println("Coroutine is started..!")
repeat(10) { //10
delay(1000L)
println("I'm working")
}
}
println("Main is started..!")
runBlocking {
println("Coroutine is done..!")
}
job.join()
suspend fun doSomethingUsefulOne() // 1
: Int {
delay(1000L)
return 1
}
suspend fun doSomethingUsefulTwo() // 2
: Int {
delay(1000L)
return 2
}
val time = measureTimeMillis //
{
val one = async { doSomethingUsefulOne() }
val two = async { doSomethingUsefulTwo() }
println("The answer is ${one.await() + two.await()}")
}
println("Completed in $time ms")
var deferred: Deferred
var sum = 0
for (i in 1..1_000_00) {
deferred = GlobalScope.async { i }
runBlocking { sum += deferred.await() }
}
suspend fun task(numbers : Int) = withContext(Dispatchers.IO) {
//long running task..
}
suspend fun fetchTwoDocs() =
coroutineScope {
val deferredOne = async { task(1) }
val deferredTwo = async { task(2) }
deferredOne.await()
deferredTwo.await()
}
launch(Dispatchers.Unconfined) { // Dispatchers .
println("Unconfined: I'm working in thread ${Thread.currentThread().name}")
}
class Activity : CoroutineScope by CoroutineScope(Dispatchers.Default) {
fun doSomething() {
repeat(10) { i ->
launch {
delay((i + 1) * 200L)
... etc
println("Coroutine $i is done")
}
}
}
}
fun main() = runBlocking<Unit> {
val activity = Activity()
activity.doSomething() // run test function
println("Launched coroutines")
delay(500L) // delay for half a second
println("Destroying activity!")
activity.destroy() // cancels all coroutines
delay(1000) // visually confirm that they don't work
}
..coroutine scope
runBlocking {
val mono //is Mono<T>
= mono(currentDispatcher() //coroutine Dispatcher) {
"OK"
}
mono.subscribe //Mono {
value ->
println(value)
}
}
..coroutine scope
runBlocking {
val job = launch {
"OK"
}
val mono = job.asMono(coroutineContext.minusKey(Job))
mono.subscribe { value ->
println(value)
}
}