Kotlin之SharedFlow和Stateflow

SharedFlow

SharedFlow是一个hot stream. sharedflow有以下特点:

  1. 没有默认值
  2. 可以保持旧值
  3. emit会挂起直到所有的订阅者处理完成
public fun  MutableSharedFlow(
    replay: Int = 0,
    extraBufferCapacity: Int = 0,
    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
)

replay: 重新发送给新订阅者之前值的个数

extraBufferCapacity:除了replay缓冲区个数之外的缓冲区的值。当有剩余空间的时候emit就不会挂起

onBufferOverflow:当extraBufferCapacity溢出时的处理。有下面三种处理方式:

public enum class BufferOverflow {
    /**
     * Suspend on buffer overflow.
     */
    SUSPEND,

    /**
     * Drop **the oldest** value in the buffer on overflow, add the new value to the buffer, do not suspend.
     */
    DROP_OLDEST,

    /**
     * Drop **the latest** value that is being added to the buffer right now on buffer overflow
     * (so that buffer contents stay the same), do not suspend.
     */
    DROP_LATEST
}

使用demo来测试这几个参数的作用:

1.测试replay的作用

fun `sharedflow Reply = 1`()= runBlocking{
    var sharedflow = MutableSharedFlow(replay = 1)
    GlobalScope.launch {
        sharedflow.emit(111)
        sharedflow.emit(222)
    }
    val job1 = GlobalScope.launch {
        delay(5000)
        sharedflow.collect{
            println("first job : $it")
        }
    }

    val job2 = GlobalScope.launch {
        delay(10000)
        sharedflow.collect{
            println("second job : $it")
        }
    }

    job1.join()
    job2.join()
}

结果:

first job : 222
second job : 222

上面的例子可以看出,设置了replay为1(默认为0),job1和job2最后打印的都是“222”

2.测试extraBufferCapacity的作用

fun `sharedflow emit suspend`() = runBlocking{
    var sharedflow = MutableSharedFlow()

    val job1 = GlobalScope.launch {
        sharedflow.collect{
            //println("${gettime()}:first job: $it")
        }
    }
    val job2 = GlobalScope.launch {
        sharedflow.collect{
            delay(5000)
            //println("${gettime()}:second job: $it")
        }
    }
    val job3 = GlobalScope.launch {
        for (i in 1..5){
            delay(500)
            println("${gettime()}:start--------emit $i")
        

你可能感兴趣的:(kotlin,开发语言,android)