1 // Copyright 2018 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 #ifndef BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_
6 #define BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_
8 #include <lib/fidl/cpp/binding_set.h>
10 #include "base/bind.h"
11 #include "base/fuchsia/service_directory.h"
16 template <typename Interface>
17 class ScopedServiceBinding {
19 // |service_directory| and |impl| must outlive the binding.
20 ScopedServiceBinding(ServiceDirectory* service_directory, Interface* impl)
21 : directory_(service_directory), impl_(impl) {
22 directory_->AddService(
23 BindRepeating(&ScopedServiceBinding::BindClient, Unretained(this)));
26 ~ScopedServiceBinding() { directory_->RemoveService(Interface::Name_); }
28 void SetOnLastClientCallback(base::OnceClosure on_last_client_callback) {
29 on_last_client_callback_ = std::move(on_last_client_callback);
30 bindings_.set_empty_set_handler(
31 fit::bind_member(this, &ScopedServiceBinding::OnBindingSetEmpty));
34 bool has_clients() const { return bindings_.size() != 0; }
37 void BindClient(fidl::InterfaceRequest<Interface> request) {
38 bindings_.AddBinding(impl_, std::move(request));
41 void OnBindingSetEmpty() {
42 bindings_.set_empty_set_handler(nullptr);
43 std::move(on_last_client_callback_).Run();
46 ServiceDirectory* const directory_;
47 Interface* const impl_;
48 fidl::BindingSet<Interface> bindings_;
49 base::OnceClosure on_last_client_callback_;
51 DISALLOW_COPY_AND_ASSIGN(ScopedServiceBinding);
54 } // namespace fuchsia
57 #endif // BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_