Jetpack datastore not synchronised data between activity and service

Viewed 142

Android application consist from visual part(activity) and bound service. Visual part is used to configure Service. Config is stored in Jetpack DataStore. Service read config on every client connection(in onBind). When new config saved from Activity, Service continues to receive old values. Service get new values only after restart. This is not what I expect to see. I expect that I can get actual datastore values from any place of application, including Service. By the way I got actual values If I read from visual part of application.

This is how I create datastore:

// On top of the file
val Context.dataStoreTest: DataStore<Preferences> by preferencesDataStore(name = "test_data_store")
val TEST_STRING = stringPreferencesKey("test_string")

This is how I save values to datastore:

class MyActivity : AppCompatActivity() {
    
    private lateinit var inputUserId: EditText
    
    override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        inputUserId = findViewById(R.id.settingsInputUserId)
        val buttonApply: Button = findViewById(R.id.settingsButtonApply)
        buttonApply.setOnClickListener {
            lifecycleScope.launch {
                applicationContext.dataStoreTest.edit {
                    it[TEST_STRING] = inputUserId.text.toString()
                }
            }
        }
    }
}

This is how I read data from Service:

class MyService : Service() {

    override fun onBind(intent: Intent): IBinder {

        GlobalScope.launch {
            val property = applicationContext.dataStoreTest.data
                .map { preferences ->
                    preferences[TEST_STRING] ?: ""
                }
                .first()
            Log.d(TAG,"property: $property")
        }
    }
}

Library I import in gradle:

implementation "androidx.datastore:datastore-preferences:1.0.0"

If it matter, when I print Context.dataStoreTest from Activity and Service I get different result: androidx.datastore.preferences.core.PreferenceDataStore@ca5d400 and androidx.datastore.preferences.core.PreferenceDataStore@dd8964b

Edit:

Probably, multi-process access is not supported yet: https://issuetracker.google.com/issues/167700860

0 Answers
Related