From f99ca3c03fbd92995ef2559198a8b7fa7721ca92 Mon Sep 17 00:00:00 2001 From: Brent Erickson Date: Mon, 30 Apr 2018 17:25:02 -0700 Subject: [PATCH] Fix a race condition in AppState that prevents listeners from being notified Summary: If someone has setup a subscription on AppState and we correct AppState via getCurrentAppState call, we need to notify all the subscribers of AppState. 1 ) Initial AppState.currentState = 'active' 2-start) Subscribe to AppState Changes 3-start) Fetch Current AppState 4 ) App Code subscribes to AppState module 5 ) App becomes backgrounded 2-finish) AppState listeners are setup (missing background event) 3-finish) AppState.currentState updated to background At this point the subscription setup in 4) will never be called with the change. AppState should always call subscribers on change This is very difficult to formally test since it's due to a race condition. We've seen this condition via bug reports but have had no local repro. [GENERAL][BUGFIX][AppState] - Fix a race condition that could prevent AppState subscription change listener from firing on initial launch Closes https://github.com/facebook/react-native/pull/18236 Differential Revision: D7823370 Pulled By: hramos fbshipit-source-id: 99b174df70262ceaf9da141d005131facd624594 --- Libraries/AppState/AppState.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Libraries/AppState/AppState.js b/Libraries/AppState/AppState.js index ecb106bb2..904bf2b0e 100644 --- a/Libraries/AppState/AppState.js +++ b/Libraries/AppState/AppState.js @@ -60,8 +60,10 @@ class AppState extends NativeEventEmitter { // prop and expose `getCurrentAppState` method directly. RCTAppState.getCurrentAppState( (appStateData) => { - if (!eventUpdated) { + // It's possible that the state will have changed here & listeners need to be notified + if (!eventUpdated && this.currentState !== appStateData.app_state) { this.currentState = appStateData.app_state; + this.emit('appStateDidChange', appStateData); } }, logError