Skip to content

Instantly share code, notes, and snippets.

@gumil
Created November 5, 2019 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gumil/73c2fd6a4b3ddca215744cb7e8b69253 to your computer and use it in GitHub Desktop.
Save gumil/73c2fd6a4b3ddca215744cb7e8b69253 to your computer and use it in GitHub Desktop.
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