Persistance

Learn how to persist different types of data

Android Blaze supports two different ways of storing data.

Firebase Firestore is used to persist data locally and also uploaded to the Firebase servers.

For key-value based pairs, use the DataStore which is kept locally on the device.

Firebase Firestore

The Firestore dependency is included in the app template.

How to read and write data

Note that the await() function is included, that can convert the listener based API to a suspend function one.

data class Customer(
    val name: String = "",
)

// reading data from customers/customerid and mapping it to Customer
val result = Firebase.firestore.collection("customers")
                .document("customerid")
                .get()
                .await()
                .toObject(Customer::class.java)

// saving data to customers/
val result = Firebase.firestore.collection("customers")
                .add(Customer(name = "Olivia Smith"))
                .await()
 

How to observe data changes

We also provide Kotlin extension functions that map the related callback API to a Flow based one.

Here is an example to listen to all documents within a collection:

Firebase
      .firestore
      .collectionFlow("customers")
      .collect {
          debugLn { "Collected ${it.documents}" }
      }
 

and here is an example of how to observe the data of a specific document:

Firebase
      .firestore
      .collection("customers")
      .documentFlow("customerId")
      .collect {
          val customer = it.toObject(Customer::class)
          debugLn { "Customer = ${customer}" }
      }

User Preferences

Android apps tend to persist user preferences as key-value pairs. We provide easy access to user preferences backed by Google’s Data Store.

 

Use the userPreferences() function to get a reference to the DataStore.

 

How to edit user preferences

Here is an example of how to create and edit a key/value pair for a boolean:

 
private preferences = userPreferences()

private val KEY_HAS_SEEN_ONBOARDING = booleanPreferencesKey(
		"has_seen_onboarding"
)

suspend fun markOnboardingAsSeen() {
    preferences.edit {
        it[KEY_HAS_SEEN_ONBOARDING] = true
    }
}
 

How to read user preferences

DataStore exposes a Flow to observe changes to user preferences. Use data to get a reference to the flow and collect it:

private preferences = userPreferences()

preferences.data.collect { prefs ->
    val value = prefs[KEY_HAS_SEEN_ONBOARDING]
    // TODO use the value
}
Did this answer your question?
😞
😐
🤩