I’m implementing a simple chat in .NET using Rx on the basis of this example:
https://blogs.claritycon.com/blog/2011/04/roll-your-own-mvc-3-long-polling-chat-site/
There’s a method that, using LongPolling waits for new messages to come:
public static void CheckForMessagesAsync(Action<List<MessageInfo>> onMessages)
{
var queued = ThreadPool.QueueUserWorkItem(new WaitCallback(parm =>
{
var msgs = new List<MessageInfo>();
var wait = new AutoResetEvent(false);
using (var subscriber = _messages.Subscribe(msg =>
{
msgs.Add(msg);
wait.Set();
}))
{
// Wait for the max seconds for a new msg
wait.WaitOne(TimeSpan.FromSeconds(MaxWaitSeconds));
}
((Action<List<MessageInfo>>)parm)(msgs);
}), onMessages);
if (!queued)
onMessages(new List<MessageInfo>());
}
Using this method I lose messages appearing between disconnecting and disposing the observer and re-connecting.
How to correctly implement this mechanism to not lose those messages?
I found a solution. I do not know whether it is the most beautiful in the world, but it works.
I created private property, so each user can have multiple sessions:
and session class:
and for each session I created class:
Each user session has own MessageQueue and is subscribed to global chat room activity subject. ChatRoomActivityMessages are persisted for each session individualy. Here is method for retrieving messages: