kotlin: flow: flow和list的相互转换

一,代码:

       //处理按钮点击事件
        binding.button1.setOnClickListener {
            runBlocking {
                // Flow转List
                flowOf(1, 2, 3, 4, 5)
                    .toList()
                    .filter { it > 2 }
                    .map { it * 2 }
                    .take(2)
                    .forEach {
                        println(it)
                    }

                // List转Flow
                listOf(1, 2, 3, 4, 5)
                    .asFlow()
                    .filter { it > 2 }
                    .map { it * 2 }
                    .take(2)
                    .collect {
                        println(it)
                    }
            }
        }

二,运行结果

两段代码的输出结果相同,如下:

image

三,总结三种创建 Flow 的方式

来自极客时间老师

image

posted @ 2025-08-02 15:00  刘宏缔的架构森林  阅读(10)  评论(0)    收藏  举报