Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
package sttp.client.asynchttpclient.monix
import monix.eval.Task
import sttp.client._
import{WebSocket, WebSocketResponse}
import scala.concurrent.duration._
object MonixWebsocketExample extends App {
.flatMap { implicit backend =>
// using a test websocket endpoint
val response: Task[WebSocketResponse[WebSocket[Task]]] = basicRequest
// 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
.flatMap(_ => ws.send(WebSocketFrame.text("Hello!")))
// describing a process, which receives a single message, prints the result
// to the console, and loops
val receive: Task[Nothing] = ws
.flatMap(t => Task(println(s"RECEIVED: $t")))
// combining two looping processes, and finishing when either completes with
// success or error
Task.race(send, receive)
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.