diff --git a/lib/Onyx.js b/lib/Onyx.js index b2f8290c9..f992b57b5 100644 --- a/lib/Onyx.js +++ b/lib/Onyx.js @@ -270,8 +270,9 @@ function keysChanged(collectionKey, collection) { * * @param {string} key * @param {mixed} data + * @param {boolean} [hasNewValue=true] */ -function keyChanged(key, data) { +function keyChanged(key, data, hasNewValue = true) { // Add or remove this key from the recentlyAccessedKeys lists if (!_.isNull(data)) { addLastAccessedKey(key); @@ -282,6 +283,11 @@ function keyChanged(key, data) { // Find all subscribers that were added with connect() and trigger the callback or setState() with the new data _.each(callbackToStateMapping, (subscriber) => { if (subscriber && isKeyMatch(subscriber.key, key)) { + // If data is not new then only trigger the callback or setState() for subscribers + // which are not initialized with Stored value + if (!hasNewValue && (subscriber.initWithStoredValues !== false)) { + return; + } if (_.isFunction(subscriber.callback)) { subscriber.callback(data, key); } @@ -475,16 +481,19 @@ function evictStorageAndRetry(error, ionMethod, ...args) { * @returns {Promise} */ function set(key, val) { - // Skip writing to storage if the value hasn't changed - if (cache.hasCacheForKey(key) && _.isEqual(val, cache.getValue(key))) { - return Promise.resolve(); - } + const shouldCacheNewValue = !cache.hasCacheForKey(key) || !_.isEqual(val, cache.getValue(key)); // Adds the key to cache when it's not available - cache.set(key, val); + if (shouldCacheNewValue) { + cache.set(key, val); + } // Optimistically inform subscribers on the next tick - Promise.resolve().then(() => keyChanged(key, val)); + Promise.resolve().then(() => keyChanged(key, val, shouldCacheNewValue)); + + if (!shouldCacheNewValue) { + return Promise.resolve(); + } // Write the thing to persistent storage, which will trigger a storage event for any other tabs open on this domain return AsyncStorage.setItem(key, JSON.stringify(val))