https://kotlinlang.org logo
s

sarvagya agarwal

09/28/2022, 4:50 PM
How can I read multiple files concurrently using coroutines ? I did this but the IDE throws me a warning saying
inappropriate blocking method call
for
FileInputStream
and
read
functions.
Copy code
suspend fun uploadFiles(files: List<File>, convertToPdf: Boolean): List<String> = coroutineScope {
	return@coroutineScope files.map {
		async {
			uploadFile(it, convertToPdf)
		}
	}.awaitAll()
}
	
@Throws(IOException::class, FileNotFoundException::class)
suspend fun uploadFile(file: File, convertToPdf: Boolean): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
	val chunk = ByteArray(4096)
	val inputStream = FileInputStream(file)
	val res: Flow<FileChunk> = flow {
		while(true) {
			val size = inputStream.read(chunk)
			if(size <= 0) break
			val fileChunk = FileChunk.newBuilder().setConvertToPdf(convertToPdf)
				.setChunk(ByteString.copyFrom(chunk, 0, size)).build()
			emit(fileChunk)
		}
	}
	val response = blockingStub.uploadFiles(res)
	return@withContext "Some String"
}
10 Views