1
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
2
// Use of this source code is governed by a BSD-style license that can be
3
// found in the LICENSE file.
5
#include "base/notification_registrar.h"
9
#include "base/notification_service.h"
11
struct NotificationRegistrar::Record {
12
bool operator==(const Record& other) const;
14
NotificationObserver* observer;
15
NotificationType type;
16
NotificationSource source;
19
bool NotificationRegistrar::Record::operator==(const Record& other) const {
20
return observer == other.observer &&
22
source == other.source;
25
NotificationRegistrar::NotificationRegistrar() {
28
NotificationRegistrar::~NotificationRegistrar() {
32
void NotificationRegistrar::Add(NotificationObserver* observer,
33
NotificationType type,
34
const NotificationSource& source) {
35
Record record = { observer, type, source };
36
registered_.push_back(record);
38
NotificationService::current()->AddObserver(observer, type, source);
41
void NotificationRegistrar::Remove(NotificationObserver* observer,
42
NotificationType type,
43
const NotificationSource& source) {
44
if (!IsRegistered(observer, type, source)) {
48
Record record = { observer, type, source };
49
RecordVector::iterator found = std::find(
50
registered_.begin(), registered_.end(), record);
51
registered_.erase(found);
53
// This can be NULL if our owner outlives the NotificationService, e.g. if our
54
// owner is a Singleton.
55
NotificationService* service = NotificationService::current();
57
service->RemoveObserver(observer, type, source);
60
void NotificationRegistrar::RemoveAll() {
61
// Early-exit if no registrations, to avoid calling
62
// NotificationService::current. If we've constructed an object with a
63
// NotificationRegistrar member, but haven't actually used the notification
64
// service, and we reach prgram exit, then calling current() below could try
65
// to initialize the service's lazy TLS pointer during exit, which throws
66
// wrenches at things.
67
if (registered_.empty())
70
// This can be NULL if our owner outlives the NotificationService, e.g. if our
71
// owner is a Singleton.
72
NotificationService* service = NotificationService::current();
74
for (size_t i = 0; i < registered_.size(); i++) {
75
service->RemoveObserver(registered_[i].observer,
77
registered_[i].source);
83
bool NotificationRegistrar::IsEmpty() const {
84
return registered_.empty();
87
bool NotificationRegistrar::IsRegistered(NotificationObserver* observer,
88
NotificationType type,
89
const NotificationSource& source) {
90
Record record = { observer, type, source };
91
return std::find(registered_.begin(), registered_.end(), record) !=