I want to store an access token in the DataStore when it is received. As such i created a class(DataStore) that handles the getting,saving and clearing. Since I want the same instance of DataStore to be available everywhere, I instantiated it in the MainApplication. My thinking was that all other classes will be able to access it with MyApplication.dataStore.
I am however getting a memory leak warning from the IDE. What is the advised way to do this?
thank you
class MyApplication : Application() {
companion object {
lateinit var dataStore: DataStore // memory leak warning here. StaticFieldLeak
}
private var tokenRetrievalScope: CoroutineScope? = null
override fun onCreate() {
super.onCreate()
dataStore= DataStore(context = this)
}
}
interface DataStoreManager {
suspend fun getToken(): String
suspend fun saveToken(token: String)
suspend fun clearToken() // Function to clear the token if needed
}
class DataStore(private val context: Context) : DataStoreManager {
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
override suspend fun getToken(): String = withContext(Dispatchers.IO) {
val preferences = context.dataStore.data.first() // Fetch Preferences
preferences[PreferencesKeys.TOKEN] ?: "" // Access token with default
}