Skip to content

Instantly share code, notes, and snippets.

@KentVu
Created July 5, 2023 03:59
Show Gist options
  • Save KentVu/a65baf115adc0fb91a13d14bee7054f9 to your computer and use it in GitHub Desktop.
Save KentVu/a65baf115adc0fb91a13d14bee7054f9 to your computer and use it in GitHub Desktop.

This test is to verify if preferencesDataStore will be updated on-the-fly. After running this, !UpdatedPref 1! and !UpdatedPref 2! was printed.

(On confirming this question on SO)

package com.github.kentvu.test
import android.util.Log
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Test
import org.junit.runner.RunWith
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
@RunWith(AndroidJUnit4::class)
class PreferencesDataStoreTest {
@Test
fun isDataStoreUpdatedOnTheFly(): Unit = runBlocking {
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
val key = stringPreferencesKey("test")
launch {
withTimeout(10.seconds) {
appContext.dataStore.data.collect { prefs ->
Log.i("DefaultSettingsTest", "Prefs updated: " + prefs[key])
}
}
}
appContext.dataStore.edit { prefs -> prefs[key] = "!UpdatedPref 1!" }
appContext.dataStore.edit { prefs -> prefs[key] = "!UpdatedPref 2!" }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment