如何设计一个Flow,它是另一个Flow的每最新5个数据的平均值?

Hel*_*oCW 3 kotlin kotlin-flow

有一个Flow每100ms就会发出一次数据,我希望得到该Flow的每最新5个数据的平均值,并将平均值转换为Double值到另一个Flow中。

如何设计流程?

代码A

   fun soundDbFlow(period: Long = 100) = flow {
        while (true) {
            var data = getAmplitude()
            emit(data)
            delay(period)
        }
    }
    .get_Average_Per5_LatestData {...} //How can I do? or is there other way?
    .map { soundDb(it) }

    private fun getAmplitude(): Int {
        var result = 0
        mRecorder?.let {
            result = it.maxAmplitude
        }
        return result
    }    
        
    private fun soundDb(input:Int, referenceAmp: Double = 1.0): Double {
        return 20 * Math.log10(input / referenceAmp)
    }
Run Code Online (Sandbox Code Playgroud)

新增内容:

致plplmax:谢谢!

我假设代码 B 会发出 1,2,3,4,5,6,7,8,9,10.....

你保证代码C会(1+2+3+4+5)/5先计算,然后(6+7+8+9+10)/5再计算,....?这是我的期望。

我担心代码 C 可能会(1+2+3+4+5)/5先计算,然后计算(2+3+4+5+6)/5,...

代码B

suspend fun soundDbFlow(period: Long) = flow {
    while (true) {
        val data = getAmplitude()
        emit(data)
        delay(period)
    }
}
Run Code Online (Sandbox Code Playgroud)

代码C

private fun reduceFlow(period: Long = 100) = flow {
    while (true) {
        val result = soundDbFlow(period)
            .take(5)
            .map { soundDb((it / 5.0).roundToInt()) }
            .reduce { accumulator, value -> accumulator + value }
        emit(result)
    }
}
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

您可以像这样编写分块运算符:

/**
 * Returns a Flow that emits sequential [size]d chunks of data from the source flow, 
 * after transforming them with [transform].
 * 
 * The list passed to [transform] is transient and must not be cached.
 */
fun <T, R> Flow<T>.chunked(size: Int, transform: suspend (List<T>)-> R): Flow<R> = flow {
    val cache = ArrayList<T>(size)
    collect {
        cache.add(it)
        if (cache.size == size) {
            emit(transform(cache))
            cache.clear()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

fun soundDbFlow(period: Long) = flow {
    while (true) {
        val data = getAmplitude()
        emit(data)
        delay(period)
    }
}
    .chunked(5) { (it.sum() / 5.0).roundToInt() }
    .map { soundDb(it) }
Run Code Online (Sandbox Code Playgroud)