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)
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!" } | |
} | |
} |