• Android flow 每秒异步返回一个值


    1. package com.example.android_flow_learn
    2. import kotlinx.coroutines.delay
    3. import kotlinx.coroutines.flow.collect
    4. import kotlinx.coroutines.flow.flow
    5. import kotlinx.coroutines.launch
    6. import kotlinx.coroutines.runBlocking
    7. import org.junit.Test
    8. import org.junit.Assert.*
    9. /**
    10. * Example local unit test, which will execute on the development machine (host).
    11. *
    12. * See [testing documentation](http://d.android.com/tools/testing).
    13. */
    14. class CoroutineTest01 {
    15. //返回了多个值 但不是异步
    16. fun simpleList(): List<Int> = listOf(1, 2, 3)
    17. //每秒 返回了多个值 也不是异步
    18. fun simpleSequence(): Sequence<Int> = sequence {
    19. for (i in 1..3) {
    20. Thread.sleep(1000) //阻塞 也不是异步
    21. //加入到序列
    22. yield(i)
    23. }
    24. }
    25. //返回了多个值 也是异步,但是是一次性返回了多个值
    26. suspend fun simpleList2(): List<Int> {
    27. delay(100)
    28. return listOf<Int>(1, 2, 3)
    29. }
    30. suspend fun simpleFlow() = flow<Int> {
    31. for (i in 1..3) {
    32. delay(1000)
    33. emit(i)
    34. }
    35. }
    36. @Test
    37. fun `test multiple values`() {
    38. // simpleList().forEach { value -> println(value) }
    39. // simpleSequence().forEach { value -> println(value) }
    40. runBlocking {
    41. // simpleList2().forEach { value -> println(value) }
    42. launch {
    43. for(k in 1..3){
    44. println("I,m not blocked $k")
    45. delay(1500)
    46. }
    47. }
    48. simpleFlow().collect{ value->
    49. println(value)
    50. }
    51. }
    52. }
    53. }

    这里面的flow挂起方式是可以不写的

    1. fun simpleFlow() = flow<Int> {
    2. for (i in 1..3) {
    3. delay(1000)
    4. emit(i)
    5. }
    6. }

     

  • 相关阅读:
    数据结构-二叉树的前、中、后序遍历
    Linux系统设置防火墙
    蓝牙智能营养电子秤解决方案
    Tomcat
    JS 是怎样运行起来的
    使用kubeadm搭建高可用集群-k8s相关组件及1.16版本的安装部署
    GCP设置Proxy来连接Cloud SQL
    vscode使用delve调试golang程序
    独自一人开发一整套 ERP 系统是什么水平?
    从-1开始实现一个中间件
  • 原文地址:https://blog.csdn.net/mp624183768/article/details/126474356