I'm trying to store value using DataStore.
class BasicDataStore(context: Context) :
PrefsDataStore(
context,
PREF_FILE_BASIC
),
BasicImpl {
override val serviceRunning: Flow<Boolean>
get() = dataStore.data.map { preferences ->
preferences[SERVICE_RUNNING_KEY] ?: false
}
override suspend fun setServiceRunningToStore(serviceRunning: Boolean) {
dataStore.edit { preferences ->
preferences[SERVICE_RUNNING_KEY] = serviceRunning
}
}
companion object {
private const val PREF_FILE_BASIC = "basic_preference"
private val SERVICE_RUNNING_KEY = booleanPreferencesKey("service_running")
}
}
@Singleton
interface BasicImpl {
val serviceRunning: Flow<Boolean>
suspend fun setServiceRunningToStore(serviceRunning: Boolean)
}
And in a Service, trying to monitor that value, here is the respective code :
private fun monitorNotificationService() {
Log.d("d--mua-entry-service","entry")
CoroutineScope(Dispatchers.IO).launch {
Log.d("d--mua-entry-service","entry scope")
basicDataStore.serviceRunning.collect{
Log.d("d--mua-entry-service","$it current status - collect")
}
basicDataStore.serviceRunning.onEach {
Log.d("d--mua-entry-service","$it current status - on each")
}
}
}
In EntryService :
init {
basicDataStore = BasicDataStore(this)
}
But it seems that onEach isn't working at all. And collect is working once, as it should. So how should I monitor/observe a flow?
Logcat :
2021-03-25 20:41:49.462 30761-30761/com.mua.roti D/d--mua-entry-service: entry
2021-03-25 20:41:49.465 30761-30900/com.mua.roti D/d--mua-entry-service: entry scope
2021-03-25 20:41:49.471 30761-30901/com.mua.roti D/d--mua-entry-service: false current status - collect