Skip to content

Commit e6475c7

Browse files
committed
Use a fold instead of a collect
1 parent 795dcfe commit e6475c7

File tree

1 file changed

+12
-10
lines changed
  • firebase-vertexai/src/main/kotlin/com/google/firebase/vertexai/common/util

1 file changed

+12
-10
lines changed

firebase-vertexai/src/main/kotlin/com/google/firebase/vertexai/common/util/kotlin.kt

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import kotlinx.coroutines.cancel
2525
import kotlinx.coroutines.currentCoroutineContext
2626
import kotlinx.coroutines.flow.Flow
2727
import kotlinx.coroutines.flow.flow
28+
import kotlinx.coroutines.flow.fold
2829

2930
/**
3031
* Removes the last character from the [StringBuilder].
@@ -67,18 +68,19 @@ internal fun Flow<ByteArray>.accumulateUntil(
6768
minSize: Int,
6869
emitLeftOvers: Boolean = false
6970
): Flow<ByteArray> = flow {
70-
val buffer = ByteArrayOutputStream()
71-
72-
collect {
73-
buffer.write(it, 0, it.size)
74-
if (buffer.size() >= minSize) {
75-
emit(buffer.toByteArray())
76-
buffer.reset()
71+
val remaining =
72+
fold(ByteArrayOutputStream()) { buffer, it ->
73+
buffer.apply {
74+
write(it, 0, it.size)
75+
if (size() >= minSize) {
76+
emit(toByteArray())
77+
reset()
78+
}
79+
}
7780
}
78-
}
7981

80-
if (emitLeftOvers && buffer.size() > 0) {
81-
emit(buffer.toByteArray())
82+
if (emitLeftOvers && remaining.size() > 0) {
83+
emit(remaining.toByteArray())
8284
}
8385
}
8486

0 commit comments

Comments
 (0)