Skip to content

Instantly share code, notes, and snippets.

@programisti
Last active March 24, 2016 14:32
Show Gist options
  • Save programisti/7f7fff772c7ec340804c to your computer and use it in GitHub Desktop.
Save programisti/7f7fff772c7ec340804c to your computer and use it in GitHub Desktop.
Keep Plug connection open
defmodule AlivePlug do
import Plug.Conn
def init(opts) do
opts
end
def call(conn, _opts) do
conn = send_chunked(conn, 200)
# send initial chunk
chunk(conn, "Init")
pid = start_thread
# create 10 async processes which does somthing for 5 seconds and then sends result via chunk
1..10
|> Enum.each(fn num ->
send pid, {conn, num}
end)
# send End as a symbol of last chunk
chunk(conn, "End")
conn
end
defp start_thread, do: spawn_link(fn -> thread_listener end)
defp thread_listener do
receive do
{conn, num} ->
:timer.sleep(5000)
# problem is here :(
# chunk returns {:error, :closed}
{:error, :closed} = chunk(conn, "hey")
thread_listener
_ ->
thread_listener
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment