You can use dispatchSync; there will be latency inherent in broadcasting, but this will remove the queue aspect.
How to broadcast an event to pusher instantly?
I've got a simple event set up that sends a notification to pusher.
ChatMessageSent::dispatch(
$this->id,
"public"
);
However, the issue I'm having is that the event is placed in a queue and there is about a 1 to 3 second delay of having it processed. As it is a chat, I would rather have it processed instantly. I can fix this by changing my queue driver to sync but that is not a solution when it changes everything to sync.
Is there anyway I can dispatch the event to pusher instantly without having it in a queue? Or perhaps is there a way to change the queue driver to sync for this event only?
ChatMessageSent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ChatMessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public int $id;
public string $channel;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($id, $channeld)
{
$this->id = $id;
$this->channel = $channel;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('chat.'.$this->channel);
}
}
Looks like I've fixed it by implementing ShouldBroadcastNow instead of ShouldBroadcast.
I was searching everywhere on the Events docs for it but I should've been searching on the broadcast docs! Doh.
Please or to participate in this conversation.