1 // Copyright 2014 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/metrics/user_metrics.h"
9 #include "base/lazy_instance.h"
10 #include "base/threading/thread_checker.h"
15 // A helper class for tracking callbacks and ensuring thread-safety.
20 // Records the |action|.
21 void Record(const std::string
& action
) {
22 DCHECK(thread_checker_
.CalledOnValidThread());
23 for (size_t i
= 0; i
< callbacks_
.size(); ++i
) {
24 callbacks_
[i
].Run(action
);
28 // Adds |callback| to the list of |callbacks_|.
29 void AddCallback(const ActionCallback
& callback
) {
30 DCHECK(thread_checker_
.CalledOnValidThread());
31 callbacks_
.push_back(callback
);
34 // Removes the first instance of |callback| from the list of |callbacks_|, if
36 void RemoveCallback(const ActionCallback
& callback
) {
37 DCHECK(thread_checker_
.CalledOnValidThread());
38 for (size_t i
= 0; i
< callbacks_
.size(); ++i
) {
39 if (callbacks_
[i
].Equals(callback
)) {
40 callbacks_
.erase(callbacks_
.begin() + i
);
47 base::ThreadChecker thread_checker_
;
48 std::vector
<ActionCallback
> callbacks_
;
50 DISALLOW_COPY_AND_ASSIGN(Callbacks
);
53 base::LazyInstance
<Callbacks
> g_callbacks
= LAZY_INSTANCE_INITIALIZER
;
57 void RecordAction(const UserMetricsAction
& action
) {
58 g_callbacks
.Get().Record(action
.str_
);
61 void RecordComputedAction(const std::string
& action
) {
62 g_callbacks
.Get().Record(action
);
65 void AddActionCallback(const ActionCallback
& callback
) {
66 g_callbacks
.Get().AddCallback(callback
);
69 void RemoveActionCallback(const ActionCallback
& callback
) {
70 g_callbacks
.Get().RemoveCallback(callback
);