[Storage] Blob Storage Refactoring pt 1:
[chromium-blink-merge.git] / device / usb / usb_service.cc
blob70f054d0b228e2736f5131a171e05f1170951b53
1 // Copyright 2015 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 "device/usb/usb_service.h"
7 #include "base/message_loop/message_loop.h"
8 #include "device/usb/usb_device.h"
9 #include "device/usb/usb_service_impl.h"
11 namespace device {
13 namespace {
15 UsbService* g_service;
17 } // namespace
19 // This class manages the lifetime of the global UsbService instance so that
20 // it is destroyed when the current message loop is destroyed. A lazy instance
21 // cannot be used because this object does not live on the main thread.
22 class UsbService::Destroyer : private base::MessageLoop::DestructionObserver {
23 public:
24 explicit Destroyer(UsbService* usb_service) : usb_service_(usb_service) {
25 base::MessageLoop::current()->AddDestructionObserver(this);
27 ~Destroyer() override {}
29 private:
30 // base::MessageLoop::DestructionObserver implementation.
31 void WillDestroyCurrentMessageLoop() override {
32 base::MessageLoop::current()->RemoveDestructionObserver(this);
33 delete usb_service_;
34 delete this;
35 g_service = nullptr;
38 UsbService* usb_service_;
41 void UsbService::Observer::OnDeviceAdded(scoped_refptr<UsbDevice> device) {
44 void UsbService::Observer::OnDeviceRemoved(scoped_refptr<UsbDevice> device) {
47 // static
48 UsbService* UsbService::GetInstance(
49 scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) {
50 if (!g_service) {
51 g_service = UsbServiceImpl::Create(ui_task_runner);
52 // This object will clean itself up when the message loop is destroyed.
53 new Destroyer(g_service);
55 return g_service;
58 // static
59 void UsbService::SetInstanceForTest(UsbService* instance) {
60 g_service = instance;
61 new Destroyer(instance);
64 UsbService::UsbService() {
67 UsbService::~UsbService() {
70 void UsbService::AddObserver(Observer* observer) {
71 DCHECK(CalledOnValidThread());
72 observer_list_.AddObserver(observer);
75 void UsbService::RemoveObserver(Observer* observer) {
76 DCHECK(CalledOnValidThread());
77 observer_list_.RemoveObserver(observer);
80 void UsbService::NotifyDeviceAdded(scoped_refptr<UsbDevice> device) {
81 DCHECK(CalledOnValidThread());
82 FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceAdded(device));
85 void UsbService::NotifyDeviceRemoved(scoped_refptr<UsbDevice> device) {
86 DCHECK(CalledOnValidThread());
87 FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceRemoved(device));
90 } // namespace device