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

Add folly::observer::makeStaticObserver

Summary: `makeStaticObserver` is a helper method that returns an observer that never changes in value.

Reviewed By: andriigrynenko

Differential Revision: D25254488

fbshipit-source-id: 1336d0088aff1e5abfa8160bd76e4f61b68eaed8
parent 5af34247
...@@ -98,6 +98,16 @@ Observer<observer_detail::ResultOfUnwrapObserver<F>> makeObserver(F&& creator) { ...@@ -98,6 +98,16 @@ Observer<observer_detail::ResultOfUnwrapObserver<F>> makeObserver(F&& creator) {
return unwrap(observer_detail::makeObserver(std::forward<F>(creator))); return unwrap(observer_detail::makeObserver(std::forward<F>(creator)));
} }
template <typename T>
Observer<T> makeStaticObserver(T value) {
return makeStaticObserver<T>(std::make_shared<T>(std::move(value)));
}
template <typename T>
Observer<T> makeStaticObserver(std::shared_ptr<T> value) {
return makeObserver([value = std::move(value)] { return value; });
}
template <typename T> template <typename T>
TLObserver<T>::TLObserver(Observer<T> observer) TLObserver<T>::TLObserver(Observer<T> observer)
: observer_(observer), : observer_(observer),
......
...@@ -213,6 +213,15 @@ template <typename F> ...@@ -213,6 +213,15 @@ template <typename F>
Observer<observer_detail::ResultOfUnwrapSharedPtr<F>> makeValueObserver( Observer<observer_detail::ResultOfUnwrapSharedPtr<F>> makeValueObserver(
F&& creator); F&& creator);
/**
* The returned Observer will never update and always return the passed value.
*/
template <typename T>
Observer<T> makeStaticObserver(T value);
template <typename T>
Observer<T> makeStaticObserver(std::shared_ptr<T> value);
template <typename T> template <typename T>
class TLObserver { class TLObserver {
public: public:
......
...@@ -563,6 +563,21 @@ TEST(Observer, MakeValueObserver) { ...@@ -563,6 +563,21 @@ TEST(Observer, MakeValueObserver) {
EXPECT_EQ(observedValues2, std::vector<int>({1, 2, 3})); EXPECT_EQ(observedValues2, std::vector<int>({1, 2, 3}));
} }
TEST(Observer, MakeStaticObserver) {
auto explicitStringObserver = makeStaticObserver<std::string>("hello");
EXPECT_EQ(**explicitStringObserver, "hello");
auto implicitIntObserver = makeStaticObserver(5);
EXPECT_EQ(**implicitIntObserver, 5);
auto explicitSharedPtrObserver =
makeStaticObserver<std::shared_ptr<int>>(std::make_shared<int>(5));
EXPECT_EQ(***explicitSharedPtrObserver, 5);
auto implicitSharedPtrObserver = makeStaticObserver(std::make_shared<int>(5));
EXPECT_EQ(**implicitSharedPtrObserver, 5);
}
TEST(Observer, Unwrap) { TEST(Observer, Unwrap) {
SimpleObservable<bool> selectorObservable{true}; SimpleObservable<bool> selectorObservable{true};
SimpleObservable<int> trueObservable{1}; SimpleObservable<int> trueObservable{1};
......
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