Created
November 5, 2019 16:35
-
-
Save gumil/73c2fd6a4b3ddca215744cb7e8b69253 to your computer and use it in GitHub Desktop.
This file contains 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 com.usabilla.coroutines | |
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.Job | |
import kotlinx.coroutines.async | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.catch | |
import kotlinx.coroutines.flow.collect | |
import kotlinx.coroutines.flow.flowOf | |
import kotlinx.coroutines.flow.map | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.runBlocking | |
fun main() { | |
val job = Job() | |
val scope = CoroutineScope(Dispatchers.Default + job) | |
scope.launch { | |
delay(1000) | |
worldHelloFlow().collect { | |
println(it) | |
} | |
} | |
// main thread scope | |
runBlocking { | |
// co-routine scope with a context derived from the main thread | |
// | |
// scope is the environment where the co-routine operations will run | |
// context is the origin of such environment | |
launch { | |
delay(1000) | |
worldHelloFlow().collect { | |
println(it) | |
} | |
} | |
val async = async { | |
delay(2000) | |
"async" | |
} | |
println(async.await()) | |
println("ending") | |
} | |
} | |
fun helloWorldFlow(): Flow<String> { | |
return flowOf("hello world") | |
} | |
fun worldHelloFlow(): Flow<String> { | |
return helloWorldFlow() | |
.catch { | |
println("error here") | |
} | |
.map { | |
"$it world hello" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment