Save User State

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Koala | 2024.1.1

Lesson 01: Save Simple Data

Demo: Read Data from DataStore

Episode complete

Play next episode

Next
Transcript

In this section, you’ll implement the logic to read the selected filter from DataStore.

Navigate to the DataStoreManager class. Create a new function called getSelectedFilter() that returns a Flow<String>:

fun getSelectedFilter(): Flow<String> {
  return context.dataStore.data
    .map { preferences ->
      preferences[stringPreferencesKey("filters")] ?: "All"
    }
}

The function above returns a Flow<String>. You call context.dataStore.data, which returns a Flow<Preferences>. You then call map on the Flow<Preferences> to map the Preferences to a String for your specified key. You then return the selected filter from DataStore. The stringPreferencesKey("filters") function creates a Preference.Key<String> instance. This key is used to get the selected filter from DataStore. If the selected filter isn’t found, you return “All” as the default filter.

And that’s it! You’ve successfully created a method to read data from DataStore.

Now, you’re going to call this method in the MainViewModel class to read the selected filter. The UI logic has already been handled for you. You just need to call the getSelectedFilter() method in the MainViewModel class. Head over to MainViewModel class and locate the following line:

// TODO: Fetch selected filter and update UI state

Replace it with the following code:

viewModelScope.launch {
  dataStoreManager.getSelectedFilter().collect { selectedFilter ->
    _selectedFilter.update { selectedFilter }
  }
}

In the fetch code you added, you call the DataStoreManager method getSelectedFilter(). This method call is inside the viewModelScope.launch coroutine. You then call collect on the Flow<String> returned by the getSelectedFilter() method. This will collect the selected filter from DataStore. You then update the _selectedFilter state with the selected filter. You have now implemented the logic to read the selected filter from DataStore.

Run the app again and select a filter. Close the app and open it again. The selected filter will be retained and displayed in the UI.

You have successfully implemented DataStore in your app to save and read data. That concludes this demo. Continue with the lesson for a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Read Data from DataStore Next: Conclusion