Extend `LiveView.stream_insert/3` to allow bulk insert

Right now, when using LiveView streams, if we want to add several new values to a stream, there’s no ergonomic way to do it.

My current approach is the following

Enum.reduce(list, socket, fn item, socket ->
  stream_insert(socket, :items, item)
end)

I see 2 possible approaches here, and would like to hear your opinion on:

  1. Extend stream_insert to support a list as a parameter
  2. Introduce a separate stream_bulk_insert/3 function accepting a list as a parameter instead of a single item

Thoughts? I’m not a contributor to Elixir/Phoenix/LiveView, so I’m not sure if there is a convention in place when considering single/multi item handling.

I’m open to implementing the change once we arrive at a conclusion here.

Hello and welcome to the forums!

I was also recently (like, last week!) wondering why this functionality doesn’t exist. Streams are relatively new with some bugs still being ironed out so it’s very possible the core team is just waiting for the right API to emerge. For example, I can’t think of reason not to just overload stream_insert to allow a single entity or a list. That doesn’t mean there isn’t a good reason, of course, so it may just be a matter of collecting enough feedback. And maybe there is a good reason they don’t want to include it at all, I’m unsure!

You can bulk insert items into streams using stream/4

stream(socket, :posts, posts)

https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#stream/4

2 Likes

Oh, wow. I do see that now! I also see that this was actually documented under stream_insert/4

See stream/4 for inserting multiple items at once.

Big oversight of mine :slight_smile:. Thank you, I appreciate the clarification!