Initialization in Activity#onCreate() may cause a crash or race condition
See original GitHub issueInitialization of Amplify in Activity#onCreate() may cause problems in the following scenarios though official documentation guides you to do so. Workaround is at the bottom of this issue.
- Start Activity and Amplify’s initialization happens
Activity#onCreate()
Amplify.addPlugin(AWSApiPlugin())
Amplify.configure(applicationContext)
- Hit back button
Activity#onDestroy() called
- Re-launch the App again
Activity#onCreate() called again
Amplify.addPlugin(AWSApiPlugin())
Amplify.configure(applicationContext) // this throws AmplifyException
The reason this happens is because Amplify is a singleton object and keeps its state with static boolean configured
and will not be subject to GC immediately after Activity#onDestroy() is called.
In this way, when Activity#onCreate() is called again, initialization is executed again, and a race condition occurs.
The official documentation catches the AmplifyException immediately, but because of this exception the configure per CATEGORIES is not done in Amplify#configure(), the app is obviously not in a good state.
The easiest workaround is to initialize in Application#onCreate(). This is the most realistic way. No race condition occurs because the lifetime of the Amplify object is tied to the life cycle of the Application.
// your custom application
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
try {
Amplify.addPlugin(AWSApiPlugin())
Amplify.configure(applicationContext)
} catch (e: AmplifyException) {
Log.e(TAG, e.message)
throw RuntimeException(e)
}
}
}
// don't forget to add your app class in the manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="us.shiroyama.amplifyforandroid">
<application
android:name=".MyApplication" />
</manifest>
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (4 by maintainers)
For whoever might be facing this issue right now, I’ve tried initializing the Amplify object from the Application class just as @jamesonwilliams says, the stability of the DataStore request and such on my app has gotten way better when only having this class as a singleton in the lifecycle of my app. instead of instantiating multiple object on each Activity
Yeah I actually have the following language in the couple of documentation pages I wrote - perhaps we should adopt similar language throughout the rest of the documentation: