- package com.example.android_flow_learn
-
- import kotlinx.coroutines.delay
- import kotlinx.coroutines.flow.collect
- import kotlinx.coroutines.flow.flow
- import kotlinx.coroutines.launch
- import kotlinx.coroutines.runBlocking
- import org.junit.Test
-
- import org.junit.Assert.*
-
- /**
- * Example local unit test, which will execute on the development machine (host).
- *
- * See [testing documentation](http://d.android.com/tools/testing).
- */
- class CoroutineTest01 {
- //返回了多个值 但不是异步
- fun simpleList(): List<Int> = listOf(1, 2, 3)
-
- //每秒 返回了多个值 也不是异步
- fun simpleSequence(): Sequence<Int> = sequence {
- for (i in 1..3) {
- Thread.sleep(1000) //阻塞 也不是异步
- //加入到序列
- yield(i)
- }
- }
-
- //返回了多个值 也是异步,但是是一次性返回了多个值
- suspend fun simpleList2(): List<Int> {
- delay(100)
- return listOf<Int>(1, 2, 3)
-
- }
-
- suspend fun simpleFlow() = flow<Int> {
- for (i in 1..3) {
- delay(1000)
- emit(i)
- }
- }
-
-
- @Test
- fun `test multiple values`() {
- // simpleList().forEach { value -> println(value) }
- // simpleSequence().forEach { value -> println(value) }
- runBlocking {
- // simpleList2().forEach { value -> println(value) }
-
- launch {
- for(k in 1..3){
- println("I,m not blocked $k")
- delay(1500)
- }
- }
- simpleFlow().collect{ value->
- println(value)
- }
-
-
-
- }
-
-
- }
- }
这里面的flow挂起方式是可以不写的
- fun simpleFlow() = flow<Int> {
- for (i in 1..3) {
- delay(1000)
- emit(i)
- }
- }
