我尝试使用 Kotlin 的Flow
类作为消息队列,将数据从生产者(相机)传输到在单独的协程上运行的一组工作人员(图像分析器)。
在我的例子中,生产者是一台相机,并且运行速度比工作人员快得多。应通过丢弃数据来处理背压,以便图像分析器始终对来自相机的最新图像进行操作。
使用通道时,此解决方案有效,但看起来很混乱,并且没有为我提供在相机和分析仪之间转换数据的简单方法(如flow.map
)。
class ImageAnalyzer<Result> {
fun analyze(image: Bitmap): Result {
// perform some work on the image and return a Result. This can take a long time.
}
}
class CameraAdapter {
private val imageChannel = Channel<Bitmap>(capacity = Channel.RENDEZVOUS)
private val imageReceiveMutex = Mutex()
// additional code to make this camera work and listen to lifecycle events of the enclosing activity.
protected fun sendImageToStream(image: CameraOutput) {
// use channel.offer to ensure the latest …
Run Code Online (Sandbox Code Playgroud)