Skip to content

Instantly share code, notes, and snippets.

@adamw adamw/sttp4.scala
Last active Oct 15, 2019

Embed
What would you like to do?
package sttp.client.asynchttpclient.monix
import monix.eval.Task
import sttp.client._
import sttp.client.ws.{WebSocket, WebSocketResponse}
import monix.execution.Scheduler.Implicits.global
import sttp.model.ws.WebSocketFrame
import scala.concurrent.duration._
object MonixWebsocketExample extends App {
AsyncHttpClientMonixBackend()
.flatMap { implicit backend =>
// using a test websocket endpoint
val response: Task[WebSocketResponse[WebSocket[Task]]] = basicRequest
.get(uri"wss://echo.websocket.org")
.openWebsocket(MonixWebSocketHandler())
// the "response" is an effect once which will store the websocket instance,
// once the websocket is established
response.flatMap { r =>
println("Websocket established!")
val ws: WebSocket[Task] = r.result
// describing a process, which sleeps for one second, sends a message, and
// loops
val send: Task[Nothing] = Task
.sleep(1.second)
.flatMap(_ => ws.send(WebSocketFrame.text("Hello!")))
.loopForever
// describing a process, which receives a single message, prints the result
// to the console, and loops
val receive: Task[Nothing] = ws
.receiveText()
.flatMap(t => Task(println(s"RECEIVED: $t")))
.loopForever
// combining two looping processes, and finishing when either completes with
// success or error
Task.race(send, receive)
}
}
.runSyncUnsafe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.