54 lines
1.5 KiB
Kotlin
54 lines
1.5 KiB
Kotlin
import io.ktor.client.HttpClient
|
|
import io.ktor.client.plugins.websocket.WebSockets
|
|
import io.ktor.client.plugins.websocket.webSocket
|
|
import io.ktor.websocket.Frame
|
|
import io.ktor.websocket.readText
|
|
import kotlinx.coroutines.CompletableDeferred
|
|
import kotlinx.coroutines.CoroutineScope
|
|
import kotlinx.coroutines.Deferred
|
|
import kotlinx.coroutines.flow.*
|
|
import kotlinx.coroutines.launch
|
|
import java.time.Instant
|
|
import io.ktor.client.engine.cio.CIO as ClientCIO
|
|
|
|
suspend fun CoroutineScope.aggregateFromService(url: String): List<Instant> {
|
|
val client = HttpClient(ClientCIO) {
|
|
install(WebSockets)
|
|
}
|
|
|
|
val result = CompletableDeferred<List<Instant>>()
|
|
|
|
launch {
|
|
client.webSocket(url) {
|
|
val res = incoming.receiveAsFlow()
|
|
.filterIsInstance<Frame.Text>()
|
|
.take(3)
|
|
.map { Instant.parse(it.readText()) }
|
|
.toList()
|
|
|
|
result.complete(res)
|
|
}
|
|
}
|
|
|
|
return result.await()
|
|
}
|
|
|
|
//suspend fun aggregateFromServiceAsync(url: String): Deferred<List<Instant>> {
|
|
// val client = HttpClient(ClientCIO) {
|
|
// install(WebSockets)
|
|
// }
|
|
//
|
|
// val result = CompletableDeferred<List<Instant>>()
|
|
//
|
|
// client.webSocket(url) {
|
|
// val res = incoming.consumeAsFlow()
|
|
// .filterIsInstance<Frame.Text>()
|
|
// .take(3)
|
|
// .map { Instant.parse(it.readText()) }
|
|
// .toList()
|
|
//
|
|
// result.complete(res)
|
|
// }
|
|
//
|
|
// return result
|
|
//} |