-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBTDataTransferService.kt
46 lines (40 loc) · 1.31 KB
/
BTDataTransferService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.sdevprem.bluetoothchat.data.chat
import android.bluetooth.BluetoothSocket
import com.sdevprem.bluetoothchat.domain.chat.BTMsg
import com.sdevprem.bluetoothchat.domain.chat.TransferFailedException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import java.io.IOException
class BTDataTransferService(
private val socket: BluetoothSocket
) {
fun listenForIncomingMessage(): Flow<BTMsg> = flow {
if (!socket.isConnected)
return@flow
val buffer = ByteArray(1024)
while (true) {
val byteCount = try {
socket.inputStream.read(buffer)
} catch (e: IOException) {
throw TransferFailedException
}
emit(
buffer
.decodeToString(endIndex = byteCount)
.toBTMsg(isFromLocalUser = false)
)
}
}.flowOn(Dispatchers.IO)
suspend fun sendMsg(bytes: ByteArray): Boolean = withContext(Dispatchers.IO) {
return@withContext try {
socket.outputStream.write(bytes)
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
}