Skip to content

Commit 79596a9

Browse files
committed
feat: run streaming read/write operations in a Kotlin coroutine (#48)
1 parent 8a94543 commit 79596a9

File tree

2 files changed

+23
-32
lines changed

2 files changed

+23
-32
lines changed

packages/react-native-fast-io/android/src/main/java/com/margelo/nitro/fastio/HybridInputStream.kt

+21-25
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,29 @@ import com.margelo.nitro.core.ArrayBuffer
44
import com.margelo.nitro.core.Promise
55
import java.io.InputStream
66

7-
class HybridInputStream(private val stream: InputStream) : HybridInputStreamSpec() {
7+
class HybridInputStream(public val stream: InputStream) : HybridInputStreamSpec() {
88
override fun read(): Promise<ArrayBuffer> {
9-
return Promise<ArrayBuffer>().apply {
10-
try {
11-
val bytes = ByteArray(HybridStreamFactory.BUFFER_SIZE)
12-
val bytesRead = stream.read(bytes, 0, bytes.size)
13-
14-
when {
15-
bytesRead == -1 -> {
16-
// End of stream
17-
resolve(ArrayBuffer.allocate(0))
18-
}
19-
bytesRead > 0 -> {
20-
val arrayBuffer = ArrayBuffer.allocate(bytesRead)
21-
22-
val destBuffer = arrayBuffer.getBuffer(false)
23-
destBuffer.put(bytes, 0, bytesRead)
24-
25-
resolve(arrayBuffer)
26-
}
27-
else -> {
28-
// Error case
29-
reject(Error("Unexpected error reading stream"))
30-
}
9+
return Promise.async {
10+
val bytes = ByteArray(HybridStreamFactory.BUFFER_SIZE)
11+
val bytesRead = stream.read(bytes, 0, bytes.size)
12+
13+
when {
14+
bytesRead == -1 -> {
15+
// End of stream
16+
ArrayBuffer.allocate(0)
17+
}
18+
bytesRead > 0 -> {
19+
val arrayBuffer = ArrayBuffer.allocate(bytesRead)
20+
21+
val destBuffer = arrayBuffer.getBuffer(false)
22+
destBuffer.put(bytes, 0, bytesRead)
23+
24+
arrayBuffer
25+
}
26+
else -> {
27+
// Error case
28+
throw Error("Unexpected error reading stream")
3129
}
32-
} catch (e: Exception) {
33-
reject(Error(e.message))
3430
}
3531
}
3632
}

packages/react-native-fast-io/android/src/main/java/com/margelo/nitro/fastio/HybridOutputStream.kt

+2-7
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,8 @@ class HybridOutputStream(private val stream: OutputStream) : HybridOutputStreamS
1111
val bytes = ByteArray(buffer.size)
1212
byteBuffer.get(bytes)
1313

14-
return Promise<Unit>().apply {
15-
try {
16-
stream.write(bytes)
17-
resolve(Unit)
18-
} catch (e: Exception) {
19-
reject(Error(e.message))
20-
}
14+
return Promise.async {
15+
stream.write(bytes)
2116
}
2217
}
2318

0 commit comments

Comments
 (0)