29

i've been using jetpack datastore for a while, but then i got a problem. I want to clear data in datastore when the app is destroyed. Im using jetpack datastore to persist data only in form

i've searched that sharedPreferences has a clear() function, is there a similar function for Jetpack Datastore ? and how can i use it ?

i found clear function in datastore documentation but there is no explanation on how to use it

Pif
  • 530
  • 2
  • 10
  • 20

5 Answers5

48

Use this

dataStore.edit { 
        it.clear()
    }

Method description states

Removes all preferences from this MutablePreferences.

For proto datastore (Thanks to Amir Raza for comment)

datastore.updateData { 
    it.toBuilder().clear().build()
}
Manohar
  • 22,116
  • 9
  • 108
  • 144
40

In case anyone wants to know how to remove a specific preference

context.dataStore.edit {
    it.remove(key)
}
Wirling
  • 4,810
  • 3
  • 48
  • 78
7

Try this (for Proto DataStore):

 dataStore.updateData { obj ->
    obj.toBuilder()
        .clear()
        .build()
 }
6

If you want to delete a specific key then try this

dataStore.edit {
        if (it.contains(key)) {
            it.remove(key)
        }
    } 
  • But `it` refers to `MutablePreferences`. So `it.clear()` would clear all preferences instead of a specific key. – Wirling Mar 22 '21 at 11:08
  • It should be `it.remove(key)`, I also posted an [answer](https://stackoverflow.com/a/66746767/2212770). The contains check is also not necessary because no exception will be thrown. – Wirling Mar 22 '21 at 13:14
1

For Proto DataStore you can do:

dataStore.updateData { it.getDefaultInstance() }

It doesn't delete the file, but it's effectively the same.