Can you have a generic MessagingCenter subscripton that will accept messages from classes

LapsusLapsus USMember ✭✭

Hi,

in my application I have multiple implementations of RFID readers and I have created an Interface than encapsulates common reader actions. So for example I have interface IReader, and then classes ReaderA, ReaderB which each holds it's own implementation of different reader and their action. The reader is a singleton inside my App class. Each Reader sends a message via MessagingCenter everytime when a new tag is detected.
Example of .Send method inside ReaderA class:

MessagingCenter.Send(this, "Rfid", new CustomTag
{
    Id = "123",
    ScannedDate = DateTime.UtcNow
});

So when I subscribe to the message inside my ContentPage, this will work:

MessagingCenter.Subscribe<ReaderA, CustomTag>(this, "Rfid", (sender, item) => {
    //TODO: process result
});

But since the actual implementation of reader will vary, this won't work when my reader will use an instance of ReaderB class. I tried to use the IReader as the sender type inside the subscribe method, but with no success. I also tried to create a base class (BaseReader) and to subscribe to it, send as it, etc. and nothing works. So the botton examples will never fire:

class ReaderA : BaseReader, IReader
{
    //...

}

MessagingCenter.Subscribe<IReader, CustomTag>(this, "Rfid", async (sender, item) => {
    //TODO: process result
});
MessagingCenter.Subscribe<BaseReader, CustomTag>(this, "Rfid", async (sender, item) => {
    //TODO: process result
});

Sure I could just have a separate subscription call for my ReaderB, but I would prefer to just make one generic subscription. Is it possible to do this and how to accomplish it? Thank you for all suggestions and provided answers :)

Answers

Sign In or Register to comment.