Commit 2e214867 authored by Pranjal Raihan's avatar Pranjal Raihan Committed by Facebook GitHub Bot

Make SimpleObservable::getObserver const

Summary: Even though `SimpleObservable<T>::getObserver` lazily creates the observer, it has no side-effects and so it can be `const`.

Differential Revision: D25146628

fbshipit-source-id: f7d850aed5748a81c7cf083d489ca0d2c58be72c
parent ccc65a2e
......@@ -23,15 +23,11 @@ namespace observer {
template <typename T>
SimpleObservable<T>::SimpleObservable(T value)
: context_(std::make_shared<Context>()) {
setValue(std::move(value));
}
: SimpleObservable(std::make_shared<const T>(std::move(value))) {}
template <typename T>
SimpleObservable<T>::SimpleObservable(std::shared_ptr<const T> value)
: context_(std::make_shared<Context>()) {
setValue(std::move(value));
}
: context_(std::make_shared<Context>(std::move(value))) {}
template <typename T>
void SimpleObservable<T>::setValue(T value) {
......@@ -49,6 +45,10 @@ void SimpleObservable<T>::setValue(std::shared_ptr<const T> value) {
});
}
template <typename T>
SimpleObservable<T>::Context::Context(std::shared_ptr<const T> value)
: value_{std::move(value)} {}
template <typename T>
struct SimpleObservable<T>::Wrapper {
using element_type = T;
......@@ -68,8 +68,8 @@ struct SimpleObservable<T>::Wrapper {
};
template <typename T>
auto SimpleObservable<T>::getObserver() {
std::call_once(observerInit_, [&]() {
auto SimpleObservable<T>::getObserver() const {
folly::call_once(observerInit_, [&]() {
SimpleObservable<T>::Wrapper wrapper;
wrapper.context = context_;
ObserverCreator<SimpleObservable<T>::Wrapper> creator(std::move(wrapper));
......@@ -77,5 +77,6 @@ auto SimpleObservable<T>::getObserver() {
});
return *observer_;
}
} // namespace observer
} // namespace folly
......@@ -19,6 +19,7 @@
#include <folly/Function.h>
#include <folly/Synchronized.h>
#include <folly/experimental/observer/Observer.h>
#include <folly/synchronization/CallOnce.h>
namespace folly {
namespace observer {
......@@ -32,18 +33,21 @@ class SimpleObservable {
void setValue(T value);
void setValue(std::shared_ptr<const T> value);
auto getObserver();
auto getObserver() const;
private:
struct Context {
folly::Synchronized<std::shared_ptr<const T>> value_;
folly::Synchronized<folly::Function<void()>> callback_;
Context() = default;
explicit Context(std::shared_ptr<const T> value);
};
struct Wrapper;
std::shared_ptr<Context> context_;
std::once_flag observerInit_;
folly::Optional<Observer<typename observer_detail::Unwrap<T>::type>>
mutable folly::once_flag observerInit_;
mutable folly::Optional<Observer<typename observer_detail::Unwrap<T>::type>>
observer_;
};
} // namespace observer
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment