https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
c

Can Korkmaz

02/15/2022, 2:31 PM
The single MainActivity which extends ComponentActivity, which also hosts navigation composable, has the same lifecycle as the application right? I need the main activity to live throughout the application lifecycle since I do login and I want a val loginUser in ViewModel (MainActivity) to persist till process death.
Couldn't find the exact answer, wanted to be sure.
a

Adam Powell

02/15/2022, 2:45 PM
No, it won't. An activity instance can be recreated by the system for configuration changes or other reasons without process death being involved. A ViewModel will persist through this. However, if the activity is `finish()`ed and relaunched later (this happens by default on most versions of android when the user presses the back button at your activity's navigation root) the ViewModel will be cleared and a relaunch will get a new ViewModel without necessarily restarting the process
👍 1
Something like a login session is generally something you want to persist beyond process death and recreation anyway though
👍 2
c

Can Korkmaz

02/15/2022, 2:48 PM
Thank you for answering. So I must use savedStateHandle if I want to persist logged-in user. I store users on room database btw.
I'm planning on implementing functionality for persisting login session for extra 10 minutes after process death, and only ask login credentials after that duration so I'll use savedStateHandle at that stage for sure, was just curious If I could get away with not using savedStateHandle at this step(no 10 minutes extra persistence). Thanks again.
t

Tim Oltjenbruns

02/15/2022, 5:17 PM
I wouldn’t use savedState to handle process death, personally. I would use shared prefs for that. Shared prefs is more of an application-scope storage while savedState is more specific to a certain instance of an activity
a

Adam Powell

02/16/2022, 2:01 AM
or to bring the topic back to kotlin, androidx.datastore is a flow-native replacement for sharedpreferences 🙂
6 Views