Simple approach: If you implement your subscribe API to return a unique ID every time it is invoked, then it will be as simple as invoking unsubscribe API with that ID. Internally in simple scenario you would use a simple array to store all subscribers but with this approach you will have to store. An ID can be a simple counter that you can increment with every single subscribe call.
{ID: subscriber' callback function}
So iterate over all subscribers when you want to publish to all subscribers.
Advanced approach:
Instead of accepting a simple function name in subscribe API, accept an object of a class which should have an onMessage function (or whatever name you want to give this method). Then you can simply pass same instance of object to unsubscribe API to get yourself unregistered. When you need to notify subscriber you can invoke instance.onMessage function of all subscribers. Comparing two object reference is easy.
0
Created by TechMaze on 2020-05-03 17:43:53 +0000 UTC
Share