How can I move channel subtopic from one to another?

I have a channel called product (product: <> product_id). When a user joins channel, it gets list of ingredients of the product with product_id. And user can change product view from one to another.

Now when a user changes product view (ie, select another product), I leave channel and join new channel with new product_id in front-end. This method works fine, but I think if it is possible to do it in channel handle_in, it would be better approach.

I tried to join channel in handle_in call, but I got no luck so far…

Is it possible to move channel subtopic on handle_in call?

You can prob just join a product channel and have it handle an event that takes a product id and returns a recipe.

Something like this on the channel side.

def handle_in("new_recipe", %{"id" => id}, socket) do
  recipe = Cookbook.get_recipe(id)
  {recipe, socket}
end

You’re going to have to wire in the js yourself.

1 Like

The reason why I want to have a subtopic per product is that I want to not only show all ingredients, but I also want to show current stock level for each ingredient.

For example, if there is a product, pizza, which consists of cheese, tomato sauce and ham, I want to broadcast to the subtopic (product:product_id(pizza)), when some amount of cheese is used. So it shows accurate current inventory level.

If I just have product channel, I will have to broadcast to the product channel when any ingredient is used. Which I want to avoid…

Ok, so what are you hoping to accomplish by using handle_in instead of just joining another channel?

Theres no reason you couldn’t have 2 channels such asproducts:pizza andingredients:inventory. The logic has to go somewhere. Im my opinion broadcasting new inventory levels for ingredients to a broad channel (i.e. products, inventory, etc) isn’t such a bad idea. I’m sure there is more than one product that shares the same ingredient. If the message for ingredient inventory update is not important to the current product, discard it. Messages are like a “broadcast” radio signal. The phoenix app is broadcasting this message, if you’re tuned in you’ll get it, if not no big deal. The broadcaster doesn’t necessarily care who listening or what the listeners do with the message. So let say the products channel receive a message inventory_update with a payload of %{cheese: 10}, the listener can then decide if that’s important. If the current product has the ingredient cheese it’s relevant, if not do nothing.

Another option might be the phoenix channel intercept . You could intercept the broadcast and apply whatever filter logic there.

1 Like