Android面试题

Android面试题之kotlin热流和channel

2024-05-09  本文已影响0人  AntDream

于冷流不同,在垃圾回收之前,flow里的值都是存在内存之中,并且处于活跃状态

StateFlow

StateFlow是一个状态容器式可观察数据流,可以向其收集器发出当前状态更新和新状态更新。还可通过其value属性读取当前的状态值

SharedFlow

SharedFlow会向其中收集值得所有使用方发出数据

channel
定义概念
val channel = Channel<Int>()
    
@Test
fun `test channel` ()= runBlocking<Unit>{
    val producer = GlobalScope.launch { 
        var i = 0;
        while (true){
            delay(1000)
            channel.send(++i)
            println("send $i")
        }
    }
    val consumer = GlobalScope.launch { 
        while (true){
            val element = channel.receive()
            println("receive $element")
        }
    }
    joinAll(producer, consumer)
}
val iterator = channel.iterator()
while (iterator.hasNext()){
    val element = iterator.next()
}

//也可以这样
for (element in channel){
                
}
produce与actor
val receiveChannel: ReceiveChannel<Int> = GlobalScope.produce {
    repeat(100){
        delay(1000)
        send(it)
    }
}
val consumer = GlobalScope.launch {
    for (i in receiveChannel){
        println("receive $i")
    }
}



val sendChannel:SendChannel<Int> = GlobalScope.actor {
    while (true){
        val element = receive()
        println(element)
    }
}
val producer = GlobalScope.launch {
    for (i in 1..3){
        sendChannel.send(i)
    }
}
channel的关闭
BroadcastChannel

发送端和接收端在Channel中存在一对多的情形,从数据处理本身来说,虽然有多个接收端,但是同一个元素只会被一个接收端读到。广播则不然,多个接收端不存在互斥行为

上一篇 下一篇

猜你喜欢

热点阅读