Skip to content

Instantly share code, notes, and snippets.

@bitkid
Created October 3, 2019 13:45
Show Gist options
  • Save bitkid/c66d198c2930bd4c5dbc753cf96b4c2f to your computer and use it in GitHub Desktop.
Save bitkid/c66d198c2930bd4c5dbc753cf96b4c2f to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
data class UploadResponse(val code: Int,
val message: String,
val file: File)
fun CoroutineScope.uploadWorker(files: ReceiveChannel<File>,
responses: SendChannel<UploadResponse>) {
launch {
for (file in files) {
println("upload file ${file.name} on thread ${Thread.currentThread().name}")
// this simulates the http client call
delay(2000)
responses.send(UploadResponse(200, "done", file))
}
}
}
fun CoroutineScope.uploadResponseHandler(responses: ReceiveChannel<UploadResponse>) {
launch {
for (response in responses) {
println("got response with code ${response.code}")
}
}
}
fun CoroutineScope.uploader(files: ReceiveChannel<File>,
nrOfWorkers: Int = 3) {
val responses = Channel<UploadResponse>()
repeat(nrOfWorkers) { uploadWorker(files, responses) }
uploadResponseHandler(responses)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment