1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- #include "RUMsgCenter.h"
- #include "RUMsgSubscriber.h"
- NS_RU_BEGIN
- std::unordered_map<std::string, MsgCenter*> MsgCenter::_gMsgCenters;
- MsgCenter* MsgCenter::instance(std::string key4MsgCenter) {
- auto msgCenterGot = _gMsgCenters.find(key4MsgCenter);
- if (msgCenterGot == _gMsgCenters.end()) {
- MsgCenter* msgCenter = new MsgCenter();
- _gMsgCenters.emplace(key4MsgCenter, msgCenter);
- return msgCenter;
- }
- return msgCenterGot->second;
- }
- void MsgCenter::receiveMsg(Msg* msg)
- {
- kMsgTopic msgTopic = msg->getMsgTopic();
- int msgTopicId = (int)msgTopic;
- auto subscribersGot = _subscriberMap.find(msgTopicId);
- if (subscribersGot != _subscriberMap.end()) {
- std::list<MsgSubscriber*> subscribers = subscribersGot->second;
- for (MsgSubscriber* subscriber : subscribers) {
- subscriber->handleMsg(msg);
- }
- }
- }
- void MsgCenter::addSubscriber(kMsgTopic msgTopic, MsgSubscriber* msgSubscriber, int priority)
- {
- msgSubscriber->setPriority(msgTopic, priority);
- int msgTopicId = (int)msgTopic;
- if (_subscriberMap.find(msgTopicId) == _subscriberMap.end()) {
- std::list<MsgSubscriber*> subscribers;
- subscribers.push_back(msgSubscriber);
- _subscriberMap.emplace(msgTopicId, subscribers);
- }else{
- _subscriberMap[msgTopicId].push_back(msgSubscriber);
- _subscriberMap[msgTopicId].sort([=](MsgSubscriber* left,MsgSubscriber* right){
- return left->getPriority(msgTopic) < right->getPriority(msgTopic);
- });
- }
- }
- void MsgCenter::removeSubscriber(kMsgTopic msgTopic, MsgSubscriber* msgSubscriber)
- {
- int msgTopicId = (int)msgTopic;
- if (_subscriberMap.find(msgTopicId) == _subscriberMap.end()) {
- CCASSERT(false, "有问题");
- }else{
- _subscriberMap[msgTopicId].remove(msgSubscriber);
- }
- }
- NS_RU_END
|