Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading