简体   繁体   English

PublishSubject 与 Kotlin 协程(流/通道)

[英]PublishSubject with Kotlin coroutines (Flow/Channel)

I'm uploading files with retrofit.我正在使用 retrofit 上传文件。 I want to listen to the retrofit progress in Kotlin and show it with the progress bar on ui.我想听听Kotlin中的retrofit进度,并在ui上用进度条显示。 When I did research on this, I found a good example of this in java using PublishSubject on this page.当我对此进行研究时,我在此页面上使用 PublishSubject 在 java 中找到了一个很好的示例。 Is it possible to show progress bar when upload image via Retrofit 2? 通过 Retrofit 2 上传图片时是否可以显示进度条? I want to adapt this to my own code, but I can't decide whether I should use Flow or Channel instead of PublishSubject in Kotlin.我想将其改编为我自己的代码,但我无法决定是否应该在 Kotlin 中使用 Flow 或 Channel 而不是 PublishSubject。

My requestbody class with broadcastChannel:我的请求体 class 与广播频道:

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
    }
}

The problem is that broadcastChannel.send(progress) wants the function to suspend but the RequestBody writeTo method should not suspend.问题是broadcastChannel.send(progress)希望 function 暂停,但 RequestBody writeTo方法不应该暂停。 In this case, I am confused.在这种情况下,我很困惑。 Should I use Flow or BroadCastChannel?我应该使用 Flow 还是 BroadCastChannel? Can you help me?你能帮助我吗?

You should use MutableStateFlow:你应该使用 MutableStateFlow:

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

Then:然后:

getProgress.value = progress

See more: StateFlow and SharedFlow查看更多: StateFlow 和 SharedFlow

val getProgress = MutableSharedFlow<Float>(extraBufferCapacity = 1) getProgress.tryEmit(progress)

Using broadcast to publish the progress.使用广播发布进度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM