Skip to content

User Messages don't seem to work and there is no doc to how to use it correctly #23

Description

@brandonpollack23
import gleam/bytes_builder
import gleam/erlang/process
import gleam/int
import gleam/io
import gleam/iterator
import gleam/option.{None, Some}
import gleam/otp/actor
import gleam/otp/task
import glisten

pub const clrf = <<"\r\n":utf8>>

type MyMessage {
  Integer(i: Int)
  String(s: String)
}

pub fn main() {
  io.println("Logs from your program will appear here!")

  let int_subject = process.new_subject()
  let string_subject = process.new_subject()
  let selector =
    process.new_selector()
    |> process.selecting(int_subject, Integer)
    |> process.selecting(string_subject, String)

  let assert Ok(subject) =
    glisten.handler(fn(_conn) { #(Nil, Some(selector)) }, fn(msg, state, conn) {
      case msg {
        glisten.Packet(_) -> io.debug("Received a packet")
        glisten.User(Integer(some_int)) ->
          io.debug("Received a user message int: " <> int.to_string(some_int))
        glisten.User(String(s)) ->
          io.debug("Received a user message string: " <> s)
      }

      let assert Ok(_) =
        bytes_builder.new()
        |> bytes_builder.append(<<"HTTP/1.1 200 OK":utf8, clrf:bits>>)
        |> bytes_builder.append(clrf)
        |> glisten.send(conn, _)

      actor.continue(state)
    })
    |> glisten.serve(4221)

  task.async(fn() {
    process.sleep(1000)
    process.send(int_subject, 42)
    process.send(string_subject, "Hello, world!")
  })

  iterator.repeatedly(fn() {
    case process.select(selector, 5000) {
      Ok(Integer(some_int)) ->
        io.debug("Received a user message int: " <> int.to_string(some_int))
      Ok(String(s)) -> io.debug("Received a user message string: " <> s)
      Error(_) -> io.debug("ERROR")
    }
  })
  |> iterator.run

  process.sleep_forever()
}

These messages are (naturally since the subject is created on the initial process) not sent to the handler. How can we achieve this?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions