当前位置:网站首页>Kotlin coroutine asynchronous flow
Kotlin coroutine asynchronous flow
2022-06-23 23:27:00 【Yellow hair burning under snow】
runBlocking
because launch Only in CoroutineScope In a statement
runBlocking Its name means the thread that runs it ( In this case, the main thread ) Blocked during call , until runBlocking All processes in {…} Complete their execution . You often see this at the top of your application runBlocking, This is rarely used in real code , Because threads are expensive resources , Blocking them is inefficient , And it is usually not desirable .

runBlocking {
launch {
delay(1000)
println("word!")
}
println("Helllo")
}
Helllo
word!
extract launch{…} To a separate function
fun main(args: Array<String>) {
runBlocking {
launch {
doWorld() }
println("Helllo")
}
}
suspend fun doWorld(){
delay(1000)
println("word!")
}
Helllo
word!
Used in any pending function coroutineScope
fun main(args: Array<String>) {
runBlocking {
doWorld()
}
}
suspend fun doWorld() = coroutineScope {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Hello
World!
coroutineScope The builder can perform multiple concurrent operations
fun main(args: Array<String>) {
runBlocking {
doWorld()
println("Done")
}
}
suspend fun doWorld() = coroutineScope {
launch {
delay(2000L)
println("World 2")
}
launch {
delay(1000L)
println("World 1")
}
println("Hello")
}
Hello
World 1
World 2
Don
Wait for the subprocess to complete , And then print “Done” character string
runBlocking {
val job = launch {
// launch a new coroutine and keep a reference to its Job
delay(1000L)
println("World!")
}
println("Hello")
job.join() // wait until child coroutine completes
println("Done")
}
Hello
World!
Done
Combine pending functions , After getting every condition , At the conclusion
fun main() = runBlocking<Unit> {
//sampleStart
val time = measureTimeMillis {
println("The answer is ${concurrentSum()}")
}
println("Completed in $time ms")
//sampleEnd
}
suspend fun concurrentSum(): Int = coroutineScope {
val one = async {
doSomethingUsefulOne() }
val two = async {
doSomethingUsefulTwo() }
one.await() + two.await()
}
suspend fun doSomethingUsefulOne(): Int {
delay(1000L) // Suppose we do something useful here
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // Suppose we do something useful here
return 29
}
The answer is 42
Completed in 1017 ms
Asynchronous flow Flow count down
@RequiresApi(Build.VERSION_CODES.N)
fun main(args: Array<String>) {
runBlocking {
launch {
val ret = countdown(60_000, 2_000) {
remianTime ->
println(" The rest of the time $remianTime")
}.onStart {
println("countdown start")
}.onCompletion {
println("countdown end")
}.reduce {
acc, value ->
println("acc$acc value $value ")
}
println("coutdown acc ret = $ret")
}
}
}
fun <T> countdown(
duration: Long,
interval: Long,
onCountdown: suspend (Long) -> T
): Flow<T> = flow {
(duration - interval downTo 0 step interval).forEach {
emit(it) }
}.onEach {
delay(interval) }
.onStart {
emit(duration) }
.map {
onCountdown(it) }
.flowOn(Dispatchers.Default)
countdown start
The rest of the time 60000
The rest of the time 58000
acckotlin.Unit value kotlin.Unit
The rest of the time 56000
acckotlin.Unit value kotlin.Unit
The rest of the time 54000
........
acckotlin.Unit value kotlin.Unit
The rest of the time 2000
acckotlin.Unit value kotlin.Unit
The rest of the time 0
acckotlin.Unit value kotlin.Unit
countdown end
coutdown acc ret = kotlin.Unit
Reference article :https://book.kotlincn.net/text/flow.html
Kotlin asynchronous | Flow Application scenarios and principles https://juejin.cn/post/6989032238079803429
边栏推荐
- Tencent lightweight + pagoda building document online preview project kkfileview
- Detailed usage of exists in SQL statements
- What is an applet container
- WebService client request failed can not create a secure xmlinputfactory
- “山大地纬杯”第十二届山东省ICPC大学生程序设计竞赛
- MySQL导致索引失效的几种情况
- Bilibili×蓝桥云课|线上编程实战赛全新上新!
- 生鲜前置仓的面子和里子
- Notes to nodejs (II)
- Flutter中的GetX状态管理用起来真的那么香吗?
猜你喜欢
SQL语句中EXISTS的详细用法大全

WebService客户端请求失败 can not create a secure xmlinputfactory

The sandbox week is coming!

Analysis on the advantages and disadvantages of the best 12 project management systems at home and abroad

Short video enters the hinterland of online music

How can wechat video numbers be broadcast live on a PC?

评估和选择最佳学习模型的一些指标总结

HAOGE's blog Road

短视频挺进在线音乐腹地

网站如何在Google建立索引
随机推荐
What are the processes, levels, stages and key points of requirements analysis in software development
Mysql中的触发器定义及语法介绍
Fabric.js 手动加粗文本iText
WebService客户端请求失败 can not create a secure xmlinputfactory
Telecommuting: how to become a master of time management| Community essay solicitation
SQL语句中EXISTS的详细用法大全
Fabric. JS manual bold text iText
C#/VB.NET Word转Text
Oracle关闭回收站
企业网站的制作流程是什么?设计和制作一个网站需要多长时间?
AIX系统月维护查什么(一)
Analysis of Alibaba cloud Tianchi competition -- prediction of o2o coupon
生鲜前置仓的面子和里子
Detailed quaternion
pyspark on hpc
FANUC机器人SRVO-050碰撞检测报警原因分析及处理对策(亲测可用)
Zynq Ultrascale+ RF Data Coverter IP配置 - ADC
Cs5213 HDMI to VGA with audio signal output scheme
2022 cloud consulting technology series storage & CDN special sharing meeting
Can postman be integrated into Ci and CD pipelines for automated interface testing?