Osman Saral
04/22/2024, 10:57 PMOsman Saral
04/22/2024, 10:57 PMval methodResultFlows: MutableMap<String, MutableSharedFlow<Incoming.MethodResponseMessage>> = mutableMapOf()
fun init() = flow {
httpClient.webSocket(
request = {
url.protocol = protocol
},
block = {
webSocketSession = this
receiveAll {
handleIncoming(it)
emit(it)
}
},
)
}
private suspend fun DefaultClientWebSocketSession.handleIncoming(incoming: Incoming) {
when (incoming) {
is Incoming.Result -> {
methodResultFlows[incoming.id]?.emit(incoming)
}
is Incoming.Updated -> {
for (id in incoming.methods) {
methodResultFlows[id]?.emit(incoming)
}
}
else -> return
}
}
inline fun <reified T : Any> call(method: String, params: JsonArray? = null) = channelFlow {
val id = randomUUID()
//I send a request to server here
sendMessage(method, params)
var last = Clock.System.now()
val logTime: (String) -> Unit = { id ->
val now = Clock.System.now()
Logger.i("DDPClient") { "***time $id $method: ${now - last}" }
last = now
}
send(MethodState.Loading)
launch {
methodResultFlows[id] = MutableSharedFlow()
methodResultFlows[id]!!.collect { responseMessage ->
when (responseMessage) {
is Incoming.Updated -> {
logTime("update")
if (!finished) {
send(MethodState.Updated)
}
}
is Incoming.Result -> {
logTime("result")
val resultObject = responseMessage.result?.let {
json.decodeFromJsonElement<T>(it)
}
send(MethodState.Success(resultObject))
}
}
}
}
awaitClose { methodResultFlows.remove(id) }
}
The log is like this on iOS
(DDPClient) ***time update (method name): 129ms
(DDPClient) ***time result (method name): 4.267s
And on Android:
(DDPClient) ***time update (method name): 129ms
(DDPClient) ***time result (method name): 467sOsman Saral
04/22/2024, 11:00 PMOsman Saral
04/24/2024, 7:57 AM