Fix Observable to not trigger unneccessary refresh if the value didn't change
[folly.git] / folly / experimental / observer / Observable-inl.h
index 231991e6adafab0c83827bd82b3061a73a4b7fb8..14d3339ae4048cadbe5447129a8599690baf860b 100644 (file)
@@ -49,7 +49,10 @@ class ObserverCreator<Observable, Traits>::Context {
     // callbacks (getting new value from observable and storing it into value_
     // is not atomic).
     std::lock_guard<std::mutex> lg(updateMutex_);
-    updateValue();
+    if (!updateValue()) {
+      // Value didn't change, so we can skip the version update.
+      return;
+    }
 
     bool expected = false;
     if (updateRequested_.compare_exchange_strong(expected, true)) {
@@ -63,12 +66,14 @@ class ObserverCreator<Observable, Traits>::Context {
   }
 
  private:
-  void updateValue() {
+  bool updateValue() {
     auto newValue = Traits::get(observable_);
+    auto newValuePtr = newValue.get();
     if (!newValue) {
       throw std::logic_error("Observable returned nullptr.");
     }
     value_.swap(newValue);
+    return newValuePtr != newValue.get();
   }
 
   folly::Synchronized<std::shared_ptr<const T>> value_;