the future is in beta

home about

Phoenix LiveView with longpoll

06 Jan 2020

One of the Phoenix Framework killer features is LiveView, which lets you build real time websites using websockets and Elixir.

Phoenix LiveView has been built on top of Phoenix Channels, which use websockets technology to let the client and the server communicate, but might not be very obvious that one can use longpolling as an alternative for websockets when setting up LiveView. As pointed out here LiveView can use the LongPoll transport like one would use for normal websockets.

On assets/js/app.js, you can pass options as a third argument to LiveSocket().

import {Socket, LongPoll} from "phoenix"
import LiveSocket from "phoenix_live_view"
let liveSocket = new LiveSocket("/admin/ticker/live", Socket, {transport: LongPoll})
liveSocket.connect()

And remember to enable longpoll in lib/demo_web/endpoint.ex.

socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [session: @session_options]],
  longpoll: true