private fun Flow.toJsonStrings(): Flow = flow { val buffer = StringBuilder() collect { byteArray -> val chunk = byteArray.toString(Charsets.UTF_8) buffer.append(chunk) while (true) { val newlineIndex = buffer.indexOf("\n") if (newlineIndex == -1) break // No complete JSON string found yet // Extract the complete JSON string val jsonString = buffer.substring(0, newlineIndex) emit(jsonString) // Remove the processed JSON string and the newline from the buffer buffer.delete(0, newlineIndex + 1) } } // Emit any remaining content in the buffer if (buffer.isNotEmpty()) { emit(buffer.toString()) } }