From c6d5381ee3ca63828b321c16baa008fd6c0b4564 Mon Sep 17 00:00:00 2001 From: Merlin Ran Date: Wed, 18 Jan 2023 07:38:35 -0500 Subject: [PATCH] add TryPublish() (#144) --- server.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/server.go b/server.go index 9774db4..d1b27af 100644 --- a/server.go +++ b/server.go @@ -122,6 +122,24 @@ func (s *Server) Publish(id string, event *Event) { } } +// TryPublish is the same as Publish except that when the operation would cause +// the call to be blocked, it simply drops the message and returns false. +// Together with a small BufferSize, it can be useful when publishing the +// latest message ASAP is more important than reliable delivery. +func (s *Server) TryPublish(id string, event *Event) bool { + stream := s.getStream(id) + if stream == nil { + return false + } + + select { + case stream.event <- s.process(event): + return true + default: + return false + } +} + func (s *Server) getStream(id string) *Stream { s.muStreams.RLock() defer s.muStreams.RUnlock()