SimpleObservable.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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/Function.h>
  18. #include <folly/Synchronized.h>
  19. #include <folly/experimental/observer/Observer.h>
  20. namespace folly {
  21. namespace observer {
  22. template <typename T>
  23. class SimpleObservable {
  24. public:
  25. explicit SimpleObservable(T value);
  26. explicit SimpleObservable(std::shared_ptr<const T> value);
  27. void setValue(T value);
  28. void setValue(std::shared_ptr<const T> value);
  29. Observer<T> getObserver();
  30. private:
  31. struct Context {
  32. folly::Synchronized<std::shared_ptr<const T>> value_;
  33. folly::Synchronized<folly::Function<void()>> callback_;
  34. };
  35. struct Wrapper;
  36. std::shared_ptr<Context> context_;
  37. std::once_flag observerInit_;
  38. folly::Optional<Observer<T>> observer_;
  39. };
  40. } // namespace observer
  41. } // namespace folly
  42. #include <folly/experimental/observer/SimpleObservable-inl.h>