Implementing message passing logic across different modules

Hello people.

I have been trying to send a message from a liveview to a phoenix controller. i am using the kernel.send/2 function. I am correctly accessing the pid of receiving process. The problem comes in receiving the message which i assume i’m doing wrongly . Here is the code for sending the message :


        output_file = file_name <> "." <> "m4a"
        receiver_pid = UserController.start()
        send(receiver_pid, {self(), output_file})

UserController.start() gets the pid of receiving process

Here is the receiving logic

defmodule JungleWeb.UserController do
  use JungleWeb, :controller

  def start do
    self()
  end

  defp listen do
    receive do
      {_sender_pid, message} ->
        IO.puts(message)
        message
    after
      5_000 ->
        IO.puts("Timeout - no messages received")
    end
  end

Can someone provide a bit more guidance
Any articles will be highly appreciated :smiling_face_with_three_hearts:

I believe you would need to have some function somewhere calling the listen/0 function you defined, which would not currently be possible since that is a private function in a module where no other function is calling it.

I have done that but still no messages are being received

what i think is wrong is the receive logic may not directly target the process mailbox that contains the message i want to retrieve

I don’t see anywhere in the code you posted that calls listen, so I don’t understand what you’re expecting to happen.

UserController.start() gets the pid of receiving process

Not in the implementation you’ve shown - all it does is call self, so there’s no separate “receiving process”.

Others have pointed out that you are not doing what you say you are doing. My question is why you want to do this? To me it does not make sense: A phoenix controller live in http handling process that is spawned for each request, so it has a very short life span.

If you want to share state between a LV and a Controller, you might want to keep the shared state in a GenServer, and have both the LV and the controller call the same GenServer.

1 Like

I’ll work on this tomorrow