MJegorovas
10/23/2020, 8:49 AMoffset
variable in this method safe to use in multiple threads?
suspend fun InputStream.readByChunks(
fileSize: Long,
chunkSize: Int,
block: suspend (bytes: ByteArray, offset: Long) -> Unit
) {
var offset = 0L
this.buffered().use { input ->
while (offset != fileSize) {
val buffer = if (offset + chunkSize < fileSize) {
ByteArray(chunkSize)
} else {
ByteArray((fileSize - offset).toInt())
}
val read = input.read(buffer)
block(buffer, offset)
offset += read
}
}
}
val semaphore = Semaphore(4)
fileInputStream.readByChunks(size, BYTE_SPLIT_SIZE_SERVER) { bytes, offset ->
semaphore.acquire()
launch(Dispatchers.Default) {
val encryptedBytes = encrypt(bytes, password)
val storeResult = server.storeFileContent(encryptedBytes, itemId, offset)
if (storeResult.isError()) {
// Cancel reading and report about unsuccessful operation
}
progress.updatePrimaryProgress()
semaphore.release()
}
}
bezrukov
10/23/2020, 8:55 AMMJegorovas
10/23/2020, 10:29 AMstoreResult.isError()
block)ephemient
10/23/2020, 12:10 PMfun InputStream.chunks(): Flow<Chunk>
cold flow instead, you could stop collecting at any point