/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include namespace folly { namespace observer { template template SimpleObservable::SimpleObservable() : context_(std::make_shared(std::make_shared())) {} template SimpleObservable::SimpleObservable(T value) : SimpleObservable(std::make_shared(std::move(value))) {} template SimpleObservable::SimpleObservable(std::shared_ptr value) : context_(std::make_shared(std::move(value))) {} template void SimpleObservable::setValue(T value) { setValue(std::make_shared(std::move(value))); } template void SimpleObservable::setValue(std::shared_ptr value) { context_->value_.swap(value); context_->callback_.withWLock([](folly::Function& callback) { if (callback) { callback(); } }); } template SimpleObservable::Context::Context(std::shared_ptr value) : value_{std::move(value)} {} template struct SimpleObservable::Wrapper { using element_type = T; std::shared_ptr context; std::shared_ptr get() { return context->value_.copy(); } void subscribe(folly::Function callback) { context->callback_.swap(callback); } void unsubscribe() { Function empty; context->callback_.swap(empty); } }; template auto SimpleObservable::getObserver() const { return observer_.try_emplace_with([&]() { SimpleObservable::Wrapper wrapper; wrapper.context = context_; ObserverCreator::Wrapper> creator(std::move(wrapper)); return unwrap(std::move(creator).getObserver()); }); } } // namespace observer } // namespace folly