kotlinretrofitokio

“Using buffer(Sink) is an error. moved to extension function” when writing Retrofit response to a File


I’m migrating to Okio 3 (pulled in via OkHttp/Retrofit). This legacy code now fails to compile:

val response = api.downloadFileFromUrl(url).execute()
val sink = Okio.buffer(Okio.sink(destination)) // <-- compile error
sink.writeAll(response.body()?.source())       // and here
sink.close()

Errors:

Using 'buffer(Sink): BufferedSink' is an error. moved to extension function
Using 'sink(File): Sink' is an error. moved to extension function
Type mismatch: inferred type is BufferedSource? but Source was expected

What is the correct, idiomatic Okio 3 way to stream a ResponseBody to a file using extension functions (and close resources safely)? A minimal working example would be great.

Environment: Kotlin 1.9.x, Retrofit 2.x, OkHttp 4.x, Okio 3.x.


Solution

  • Sample code

    import okio.buffer
    import okio.sink
    import okio.source
    import java.io.File
    import okhttp3.ResponseBody
    
    fun writeBodyToFile(respBody: ResponseBody?, dest: File) {
        val body = respBody ?: return  // handle null
        dest.sink().buffer().use { sink ->
            body.source().use { src ->
                sink.writeAll(src)
            }
        }
    }