Skip to content

Instantly share code, notes, and snippets.

@ajaychandran
Last active January 11, 2021 10:08
Show Gist options
  • Save ajaychandran/c7ba1ddd423aed826e03d7f1edd92890 to your computer and use it in GitHub Desktop.
Save ajaychandran/c7ba1ddd423aed826e03d7f1edd92890 to your computer and use it in GitHub Desktop.
Example for Airstream websocket event sources (PR #60)
import com.raquo.laminar.api.L._
import org.scalajs.dom
import scala.scalajs.js
/** @see [[https://www.websocket.org/echo.html]] */
object WebSocketTester {
private val url = "wss://echo.websocket.org/"
private val transmit = Var("hello")
private val connect = new EventBus[Boolean]
private val send = new EventBus[Unit]
private val clear = new EventBus[Unit]
private val message = new EventBus[String]
private val $transmit = send.events.sample(transmit.signal)
private val (controller, receiver, transmitter) =
WebSocketEventStream.text.open(
url,
closeObserver = message.writer.contramap[dom.CloseEvent](e => s"CLOSED: ${js.JSON.stringify(e)}"),
errorObserver = message.writer.contramap[dom.Event](e => s"CLOSED: ${js.JSON.stringify(e)}"),
openObserver = message.writer.contramap[dom.Event](e => s"OPENED: ${js.JSON.stringify(e)}"),
startObserver = message.writer.contramap[Any](_ => "CONNECTING"),
unsentObserver = message.writer.contramap[String](s => s"UNSENT: $s")
)
val view: HtmlElement =
form(
h1("WebSocket Tester"),
fieldSet(
legend("URL"),
span(
label(value := url),
button("Reconnect", onClick.preventDefault.mapToValue(true) --> connect),
button("Disconnect", onClick.preventDefault.mapToValue(false) --> connect)
)
),
fieldSet(
legend("Transmitter"),
span(
input(value <-- transmit.signal, inContext(e => onChange.preventDefault.mapTo(e.ref.value) --> transmit)),
button("Send", onClick.preventDefault.mapToValue(()) --> send)
)
),
fieldSet(
legend("Receiver"),
span(
textArea(
readOnly := true,
rows := 10,
value <-- clear.events.mapToValue(""),
inContext(e => value <-- message.events.map(s => s"${e.ref.value}\n$s"))
),
button("Clear", onClick.preventDefault.mapToValue(()) --> clear)
)
),
receiver --> message,
$transmit --> transmitter,
connect.events --> controller
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment