当前位置:网站首页>Kotlin 协程 异步 异步流
Kotlin 协程 异步 异步流
2022-06-23 22:03:00 【黄毛火烧雪下】
runBlocking
因为launch只在CoroutineScope中声明
runBlocking 的名字意味着运行它的线程(在本例中是主线程)在调用期间被阻塞,直到runBlocking中所有的协程{…}完成他们的执行。您经常会在应用程序的顶层看到这样使用runBlocking,而在真正的代码中却很少这样使用,因为线程是昂贵的资源,阻塞它们的效率很低,而且通常是不可取的。

runBlocking {
launch {
delay(1000)
println("word!")
}
println("Helllo")
}
Helllo
word!
提取launch{…}转换成一个单独的函数
fun main(args: Array<String>) {
runBlocking {
launch {
doWorld() }
println("Helllo")
}
}
suspend fun doWorld(){
delay(1000)
println("word!")
}
Helllo
word!
任何挂起函数中使用coroutineScope
fun main(args: Array<String>) {
runBlocking {
doWorld()
}
}
suspend fun doWorld() = coroutineScope {
launch {
delay(1000L)
println("World!")
}
println("Hello")
}
Hello
World!
coroutineScope构建器可以执行多个并发操作
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
等待子协程完成,然后打印“Done”字符串
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
组合挂起函数,等拿到每个条件之后,在得出结论
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) // 假设我们在这里做了些有用的事
return 13
}
suspend fun doSomethingUsefulTwo(): Int {
delay(1000L) // 假设我们在这里也做了些有用的事
return 29
}
The answer is 42
Completed in 1017 ms
异步流Flow倒计时
@RequiresApi(Build.VERSION_CODES.N)
fun main(args: Array<String>) {
runBlocking {
launch {
val ret = countdown(60_000, 2_000) {
remianTime ->
println("剩余时间$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
剩余时间60000
剩余时间58000
acckotlin.Unit value kotlin.Unit
剩余时间56000
acckotlin.Unit value kotlin.Unit
剩余时间54000
........
acckotlin.Unit value kotlin.Unit
剩余时间2000
acckotlin.Unit value kotlin.Unit
剩余时间0
acckotlin.Unit value kotlin.Unit
countdown end
coutdown acc ret = kotlin.Unit
参考文章 :https://book.kotlincn.net/text/flow.html
Kotlin 异步 | Flow 应用场景及原理 https://juejin.cn/post/6989032238079803429
边栏推荐
- 专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
- MySQL事务隔离
- The sandbox and bayz have reached cooperation to jointly drive the development of metauniverse in Brazil
- 数据解读!理想L9冲刺「月销过万」,从BBA手中抢份额
- Flutter中的GetX状态管理用起来真的那么香吗?
- WebService客户端请求失败 can not create a secure xmlinputfactory
- SQL Server Common SQL
- Apache log4j 2 reported high-risk vulnerability, coding teamed up with Tencent to protect software security
- [design] 1359- how umi3 implements plug-in architecture
- How to handle the IP inconsistency in the contact when easygbs is cascaded with the upper level
猜你喜欢

HDLBits-&gt;Circuits-&gt;Arithmetic Circuitd-&gt;3-bit binary adder

《阿里云天池大赛赛题解析》——O2O优惠卷预测

数据解读!理想L9冲刺「月销过万」,从BBA手中抢份额

国内外最好的12款项目管理系统优劣势分析

国家邮政局等三部门:加强涉邮政快递个人信息安全治理,推行隐私面单、虚拟号码等个人信息去标识化技术

The national post office and other three departments: strengthen the security management of personal information related to postal express delivery, and promote the de identification technology of per

专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!

Ambire Guide: the arbitrum odyssey begins! Week 1 - Cross Chain Bridge

C# 读取内存条占用大小,硬盘占用大小

The 12 SQL optimization schemes summarized by professional "brick moving" old drivers are very practical!
随机推荐
Recommended | January activity 2-core 4G lightweight application server, enterprise nationwide purchase 6.7 yuan / month!!!
SQL语句中EXISTS的详细用法大全
WebService客户端请求失败 can not create a secure xmlinputfactory
光大期货安全吗?开户需要什么东西?
Summary of some indicators for evaluating and selecting the best learning model
Aicon2021 | AI technology helps content security and promotes the healthy development of Internet Environment
Detailed quaternion
反序列化——php反序列化
[js] 去除小数点后面多余的零
The fortress computer is connected to the server normally, but what's wrong with the black screen? What should I do?
How to set up links for website construction how to build a website
How to set the website construction title bar drop-down
How to judge the video frame type in h265 in golang development
PHP timestamp
The latest February activity # 1 core 2G first year: 38 yuan / year! 2-core 4G light weight RMB 74 / year! Mysql database 19.9 yuan / year!!
Unknown character set index for field ‘255‘ received from server.
【技术干货】蚂蚁办公零信任的技术建设路线与特点
Consequences of website construction without SSL authentication are websites without SSL authentication reliable
How to use data warehouse to create time series
Million message IM system technical points sharing