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
}

--

--

--

Chief Typing Officer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Authenticate Django Apps with Another Django App Hosted Separately

Price Comparator (IV)

Are You New to WordPress? Most Vital Things to Know

Improve FB sign in

PHP 8 New Feature You Need To Know As PHP Developer

Importance of Agile Development Methodology

Masking Uploaded File Name

SSL Certificate update in Production Mobile App

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
Fedor Korotkov

Fedor Korotkov

Chief Typing Officer

More from Medium

Protobuf and gRPC In Action With Kotlin

Visiting Reactor Netty

Enable Smile serialization on requests using Spring WebClient (Kotlin)

Memory leak due to improper exception handling