2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <folly/experimental/observer/Observable.h>
24 SimpleObservable<T>::SimpleObservable(T value)
25 : context_(std::make_shared<Context>()) {
26 setValue(std::move(value));
30 SimpleObservable<T>::SimpleObservable(std::shared_ptr<const T> value)
31 : context_(std::make_shared<Context>()) {
32 setValue(std::move(value));
36 void SimpleObservable<T>::setValue(T value) {
37 setValue(std::make_shared<const T>(std::move(value)));
41 void SimpleObservable<T>::setValue(std::shared_ptr<const T> value) {
42 context_->value_.swap(value);
44 context_->callback_.withWLock([](folly::Function<void()>& callback) {
52 struct SimpleObservable<T>::Wrapper {
53 using element_type = T;
55 std::shared_ptr<Context> context;
57 std::shared_ptr<const T> get() {
58 return context->value_.copy();
61 void subscribe(folly::Function<void()> callback) {
62 context->callback_.swap(callback);
66 folly::Function<void()> empty;
67 context->callback_.swap(empty);
72 Observer<T> SimpleObservable<T>::getObserver() {
73 std::call_once(observerInit_, [&]() {
74 SimpleObservable<T>::Wrapper wrapper;
75 wrapper.context = context_;
76 ObserverCreator<SimpleObservable<T>::Wrapper> creator(std::move(wrapper));
77 observer_ = std::move(creator).getObserver();
81 } // namespace observer