SimpleObservable-inl.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2016-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <folly/experimental/observer/Observable.h>
  18. namespace folly {
  19. namespace observer {
  20. template <typename T>
  21. SimpleObservable<T>::SimpleObservable(T value)
  22. : context_(std::make_shared<Context>()) {
  23. setValue(std::move(value));
  24. }
  25. template <typename T>
  26. SimpleObservable<T>::SimpleObservable(std::shared_ptr<const T> value)
  27. : context_(std::make_shared<Context>()) {
  28. setValue(std::move(value));
  29. }
  30. template <typename T>
  31. void SimpleObservable<T>::setValue(T value) {
  32. setValue(std::make_shared<const T>(std::move(value)));
  33. }
  34. template <typename T>
  35. void SimpleObservable<T>::setValue(std::shared_ptr<const T> value) {
  36. context_->value_.swap(value);
  37. context_->callback_.withWLock([](folly::Function<void()>& callback) {
  38. if (callback) {
  39. callback();
  40. }
  41. });
  42. }
  43. template <typename T>
  44. struct SimpleObservable<T>::Wrapper {
  45. using element_type = T;
  46. std::shared_ptr<Context> context;
  47. std::shared_ptr<const T> get() {
  48. return context->value_.copy();
  49. }
  50. void subscribe(folly::Function<void()> callback) {
  51. context->callback_.swap(callback);
  52. }
  53. void unsubscribe() {
  54. Function<void()> empty;
  55. context->callback_.swap(empty);
  56. }
  57. };
  58. template <typename T>
  59. Observer<T> SimpleObservable<T>::getObserver() {
  60. std::call_once(observerInit_, [&]() {
  61. SimpleObservable<T>::Wrapper wrapper;
  62. wrapper.context = context_;
  63. ObserverCreator<SimpleObservable<T>::Wrapper> creator(std::move(wrapper));
  64. observer_ = std::move(creator).getObserver();
  65. });
  66. return *observer_;
  67. }
  68. } // namespace observer
  69. } // namespace folly