https://kotlinlang.org logo
#ktor
Title
# ktor
b

brabo-hi

01/27/2022, 11:10 PM
how to read deserialized incoming messages continuously ? or as a flow in
ktor 2.x
? Should we read in a
while(true){}
Copy code
client.wss() {
   while (true) {
      val customer = receiveDeserialized<Customer>()
   }
}
i know we could read incoming messages but as frame using
incoming.consumeAsFlow()
a

Aleksei Tirman [JB]

01/29/2022, 9:32 AM
@Daria Usova
👀 1
d

Daria Usova

01/31/2022, 6:54 AM
Thanks for the question.
receiveDeserialized
should be used with
while
. For example:
Copy code
client.wss() {
   try {
      while(true) {
        val customer = receiveDeserialized<Customer>()
      }
   } catch (t: Throwable) {
      ...
   }
}
If you wish to deserialize incoming messages in a flow, you could write something like this:
Copy code
val converter: WebsocketContentConverter = ...
val customers = incoming.consumeAsFlow()
    .map {
         converter.deserialize(
             charset = call.request.headers.suitableCharset(),
             typeInfo = typeInfo<Customer>(),
             content = it
         )
   }.collect()
b

brabo-hi

01/31/2022, 6:32 PM
Thank you for your help, 👍
👍 1
96 Views