Mirt
Mirt

Reputation: 93

Ktor http client - request progress

How do I monitor request progress in Ktor http client?

For example: I have request like this:

val response = HttpClient().get<String>("https://stackoverflow.com/")

and I want to monitor request progress with progress bar like this:

fun progress(downloaded: Long, contentLength: Long) {
    // Update progress bar or whatever
}

How do I set progress() to be called by HttpClient?

edit: This is Kotlin Multiplatform project. Relevant dependencies are:

implementation 'io.ktor:ktor-client-core:1.2.5'
implementation 'io.ktor:ktor-client-cio:1.2.5'

Upvotes: 9

Views: 3084

Answers (2)

TangSir
TangSir

Reputation: 197

How to emit the download progress into a Flow?

I want to observe the download progress by a Flow, so I write a function like this:

suspend fun downloadFile(file: File, url: String): Flow<Int>{
        val client = HttpClient(Android)
        return flow{
            val httpResponse: HttpResponse = client.get(url) {
                onDownload { bytesSentTotal, contentLength ->
                    val progress = (bytesSentTotal * 100f / contentLength).roundToInt()
                    emit(progress)
                }
            }
            val responseBody: ByteArray = httpResponse.receive()
            file.writeBytes(responseBody)
        }
}

but the onDownload will be called only once. If I remove the emit(progress) it will work.

@andrey-aksyonov

Upvotes: 1

Andrey Aksyonov
Andrey Aksyonov

Reputation: 331

Starting with Ktor 1.6.0, you can react to download progress change using the onDownload extension function exposed by HttpRequestBuilder:

val channel = get<ByteReadChannel>("https://ktor.io/") {
    onDownload { bytesSentTotal, contentLength ->
        println("Received $bytesSentTotal bytes from $contentLength")
    }
}

There is also the onUpload function that can be used to display upload progress:

onUpload { bytesSentTotal, contentLength ->
    println("Sent $bytesSentTotal bytes from $contentLength")
}

Here are runnable examples from the Ktor documentation:

Upvotes: 7

Related Questions