Turbo Streams - How to properly structure logic for live updates from background job?

I’ve just posted this on Reddit, but now realized this is probably much better place to ask Hotwire related questions.

I am testing Hotwire. My action spawns a background worker and renders an action. This action connects to the stream. Worker sends updates and new information are rendered correctly, as they arrive. In general this works pretty well.

Now, the problem is, that there is a period between spawning a job, and subscribing to the stream. Sometimes the background job starts to stream the updates before the action manages to establish a connection. Some of the information gets lost (does not appear on the page - due to an obvious reason).

I am not sure, what would be the correct way to approach this issue. Delaying the worker might resolve the issue in most cases, but it’s not really a very professional solution. It would be also quite hard to estimate resonable delay.

I was tinkering with monkey-patching the subscribed method in Turbo::StreamsChannel. As far as I am aware there is no way to revert the signed_stream_name so I would have to actually store it somewhere. Besides, this gets quite hairy pretty fast and doesn’t fell like a right way to do things. The logic to check what was actually streamed before the client has connected would have to be quite complex.

I am not quite sure if I explained the issue in enough detail. Presenting the code doesn’t really make much sense either, as the logic isn’t very complicated.

Does anyone have an idea how to approach this?

1 Like

Is subscribing to the stream earlier (ex: before the job spawns) an option?