PublishSubject 与 Kotlin 协程 (Flow/Channel)

PublishSubject with Kotlin coroutines (Flow/Channel)

我正在上传经过改造的文件。我想在 Kotlin 中聆听改造进度,并在 ui 上用进度条显示。当我对此进行研究时,我在 java using PublishSubject on this page 中找到了一个很好的例子。 我想使它适应我自己的代码,但我无法决定在 Kotlin 中我应该使用 Flow 还是 Channel 而不是 PublishSubject。

我的请求体 class 和 broadcastChannel:

class ProgressRequestBody : RequestBody {
    val mFile: File
    val ignoreFirstNumberOfWriteToCalls : Int

    constructor(mFile: File) : super(){
        this.mFile = mFile
        ignoreFirstNumberOfWriteToCalls = 0
    }

    constructor(mFile: File, ignoreFirstNumberOfWriteToCalls : Int) : super(){
        this.mFile = mFile
        this.ignoreFirstNumberOfWriteToCalls = ignoreFirstNumberOfWriteToCalls
    }
    var numWriteToCalls = 0

    val getProgress = BroadcastChannel<Float>(1)


    override fun contentType(): MediaType? {
        return "image/*".toMediaTypeOrNull()
    }

    @Throws(IOException::class)
    override fun contentLength(): Long {
        return mFile.length()
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        numWriteToCalls++

        val fileLength = mFile.length()
        val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
        val `in` = FileInputStream(mFile)
        var uploaded: Long = 0

        try {
            var read: Int
            var lastProgressPercentUpdate = 0.0f
            read = `in`.read(buffer)
            while (read != -1) {

                uploaded += read.toLong()
                sink.write(buffer, 0, read)
                read = `in`.read(buffer)

                // when using HttpLoggingInterceptor it calls writeTo and passes data into a local buffer just for logging purposes.
                // the second call to write to is the progress we actually want to track
                if (numWriteToCalls > ignoreFirstNumberOfWriteToCalls ) {
                    val progress = (uploaded.toFloat() / fileLength.toFloat()) * 100f
                    //prevent publishing too many updates, which slows upload, by checking if the upload has progressed by at least 1 percent
                    if (progress - lastProgressPercentUpdate > 1 || progress == 100f) {
                        // publish progress
                        getProgress.send(progress)
                        lastProgressPercentUpdate = progress
                    }
                }
            }
        } finally {
            `in`.close()
        }
    }


    companion object {

        private val DEFAULT_BUFFER_SIZE = 2048
    }
}

问题是 broadcastChannel.send(progress) 希望函数暂停但 RequestBody writeTo 方法不应该暂停。在这种情况下,我很困惑。我应该使用 Flow 还是 BroadCastChannel?你能帮帮我吗?

你应该使用 MutableStateFlow:

val getProgress = MutableStateFlow<Float>(0f) // Initial value is 0

然后:

getProgress.value = progress

查看更多:StateFlow and SharedFlow

val getProgress = MutableSharedFlow<Float>(extraBufferCapacity = 1)

getProgress.tryEmit(progress)