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.
4 
5 #ifndef SRC_BASE_NOTIFICATION_REGISTRAR_H_
6 #define SRC_BASE_NOTIFICATION_REGISTRAR_H_
7 
8 #include <cstdint>
9 #include <vector>
10 
11 #include "base/notification_type.h"
12 
13 class NotificationObserver;
14 class NotificationSource;
15 
16 // Aids in registering for notifications and ensures that all registered
17 // notifications are unregistered when the class is destroyed.
18 //
19 // The intended use is that you make a NotificationRegistrar member in your
20 // class and use it to register your notifications instead of going through the
21 // notification service directly. It will automatically unregister them for
22 // you.
23 class NotificationRegistrar {
24  public:
25   // This class must not be derived from (we don't have a virtual destructor so
26   // it won't work). Instead, use it as a member in your class.
27   NotificationRegistrar();
28   ~NotificationRegistrar();
29 
30   // Wrappers around NotificationService::[Add|Remove]Observer.
31   void Add(NotificationObserver* observer,
32            NotificationType type,
33            const NotificationSource& source);
34   void Remove(NotificationObserver* observer,
35               NotificationType type,
36               const NotificationSource& source);
37 
38   // Unregisters all notifications.
39   void RemoveAll();
40 
41   // Returns true if no notifications are registered.
42   bool IsEmpty() const;
43 
44   // Returns true if there is already a registered notification with the
45   // specified details.
46   bool IsRegistered(NotificationObserver* observer,
47                     NotificationType type,
48                     const NotificationSource& source);
49 
50  private:
51   struct Record;
52 
53   // We keep registered notifications in a simple vector. This means we'll do
54   // brute-force searches when removing them individually, but individual
55   // removal is uncommon, and there will typically only be a couple of
56   // notifications anyway.
57   typedef std::vector<Record> RecordVector;
58 
59   // Lists all notifications we're currently registered for.
60   RecordVector registered_;
61 };
62 
63 #endif  // SRC_BASE_NOTIFICATION_REGISTRAR_H_
64