androidkotlinandroid-multi-module

How to store access token in memory, variable or SavedStateHandle?


Problem with storing Access token in SavedStateHandle is that we are coupling presentation layer with the data layer, as what management of access token is task of data layer.

I haven't found much issue's with variable approach, but just thought of using SavedStateHandle as a possible approach.


Solution

  • Best Approach: In-Memory Cache in Repository Store the access token in a repository with an in-memory variable:

    class TokenRepository {
        private var accessToken: String? = null
    
        fun getAccessToken() = accessToken
        fun saveAccessToken(token: String) { accessToken = token }
        fun clearAccessToken() { accessToken = null }
    }
    

    In your ViewModel, interact with the repository:

    class MyViewModel(private val tokenRepository: TokenRepository) : ViewModel() {
        fun getToken() = tokenRepository.getAccessToken()
        fun setToken(token: String) = tokenRepository.saveAccessToken(token)
    }
    

    Why This Works:

    1. Decouples presentation from data layers.
    2. Handles tokens efficiently for session-limited use.
    3. Synchronize with persistent storage (e.g., SharedPreferences) for longer-lived tokens if needed.

    Avoid SavedStateHandle for token storage due to process-death limitations and UI coupling concerns. Use it only for UI-specific state.