android / codelab-android-datastore

Apache License 2.0
227 stars 105 forks source link

dataStore.data.colletc{} has been waiting for new data #46

Closed LiJianShu0826 closed 2 years ago

LiJianShu0826 commented 2 years ago

i'm write a demo about preferencesDataStore

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

class MainActivity : ComponentActivity() {

    val EXAMPLE_COUNTER = intPreferencesKey("example_counter")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.readBtn.setOnClickListener {
            val exampleCounterFlow: Flow<Int> = dataStore.data
                .map { preferences ->
                    preferences[EXAMPLE_COUNTER] ?: 0
                }
            lifecycleScope.launch {
                //1⃣️
                exampleCounterFlow.collect { value ->
                    Toast.makeText(
                        this@MainActivity,
                        "$value",
                        Toast.LENGTH_LONG
                    ).show()
                    lifecycleScope.cancel()
                }
            }
        }

        binding.saveBtn.setOnClickListener {
            lifecycleScope.launch {
                dataStore.edit { settings ->
                    //2⃣️
                    val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
                    settings[EXAMPLE_COUNTER] = currentCounterValue + 1
                }
            }
        }
    }
}

The coroutine has bean suspend at 1⃣️. but no resume, so when i transfer val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0 at 2⃣️.it will transfer collect code block again!

rohitsat13 commented 2 years ago

Could you clarify what you're trying to do? lifecycleScope.launch { //1⃣️ exampleCounterFlow.collect { value -> Toast.makeText( this@MainActivity, "$value", Toast.LENGTH_LONG ).show() lifecycleScope.cancel() } } This should collect the first element then cancel the lifecycle scope. Why are you cancelling the lifecycle scope?