Asynchronous downloads from Google Storage with Kotlin

val storage = ... // instance of com.google.cloud.storage.Storage
val blobInfo = ...
val reader = storage.reader(blobInfo.blobId)
val buffer = ByteBuffer.allocate(bufferSize)
while (true) {
buffer.clear()
val bytesRead = withContext(Dispatchers.IO) {
reader.read(buffer)
}
buffer.flip()
if (bytesRead <= 0) {
break
}
// do stuff
}
val storage = ... // instance of com.google.cloud.storage.Storage
val blobInfo = ...
val httpClient = ... // Ktor client
// create a read-only signed URL valid for 1 hour
val blobUrl = storage.signUrl(
blobInfo,
1,
TimeUnit.HOURS,
Storage.SignUrlOption.httpMethod(HttpMethod.GET),
Storage.SignUrlOption.withV4Signature()
)
val reader = httpClient.get<ByteReadChannel>(blobUrl)
reader.read(min = bufferSize) { buffer->
// do stuff
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store