more coroutines demos

This commit is contained in:
Alexander Nozik 2021-04-29 20:51:37 +03:00
parent 473cef530e
commit cbfecbb8ad
3 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package demos
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.isActive
import kotlin.coroutines.CoroutineContext
import kotlin.random.Random
class ChannelDemo: CoroutineScope{
override val coroutineContext: CoroutineContext
get() = TODO("Not yet implemented")
val channel = Channel<Double>()
val channel2 = Channel<Double>()
suspend fun produce(){
while (isActive){
channel.send(Random.nextDouble())
}
}
suspend fun consume(){
// while (isActive){
// val res = channel.receive()
// println(res)
// }
for(res in channel){
println(res)
channel2.send(res)
}
}
}

View File

@ -0,0 +1,52 @@
package demos
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
//fun doSomething(){
// coroutineContext
//}
suspend fun doSomethingSuspended(name: String) {
println("$name : ")
println(coroutineContext)
println(coroutineContext[Job])
}
class MyApplication(parentContext: CoroutineContext) : CoroutineScope {
override val coroutineContext: CoroutineContext =
parentContext + SupervisorJob(parentContext[Job]) + CoroutineName("MyApplication")
}
fun main(): Unit {
runBlocking {
val myApplication = MyApplication(coroutineContext)
myApplication.launch(Dispatchers.IO + CoroutineName("A")) {
delay(20)
doSomethingSuspended("A")
}
// val job = myApplication.launch(CoroutineName("B")) {
// doSomethingSuspended("B")
// error("F")
// }
val result = async {
delay(20)
22
}
println(result.await())
// supervisorScope {
// launch(CoroutineExceptionHandler { coroutineContext, throwable ->
// println("Fail")
// }) {
// error("ddd")
// }
// }
}
}

View File

@ -0,0 +1,50 @@
package demos
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlin.random.Random
suspend fun main() {
coroutineScope {
val f = flow {
while (true) {
val value = Random.nextDouble()
delay(10)
println("Emitted $value!")
emit(value)
}
}
val res = f
.map { it + 1 }
.flatMapConcat {
flow {
emit(it)
emit(it+1)
}
}.onEach {
delay(20)
println("Collected $it!")
}.launchIn(this)
delay(500)
res.cancel()
val f2 = channelFlow<Int> {
repeat(10){
val value = Random.nextInt()
println("Hot int: $value")
send(value)
}
}
f2.take(1).collect {
}
val sharedFlow = MutableSharedFlow<Double>()
sharedFlow.emit(2.0)
}
}