Skip to content

Instantly share code, notes, and snippets.

@adamw
Last active October 15, 2019 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamw/4d62ae21353a4671848ab78736d51463 to your computer and use it in GitHub Desktop.
Save adamw/4d62ae21353a4671848ab78736d51463 to your computer and use it in GitHub Desktop.
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