Pif
Pif

Reputation: 602

How to clear jetpack datastore data on specific condition

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

Upvotes: 35

Views: 21077

Answers (8)

Goran Horia Mihail
Goran Horia Mihail

Reputation: 3645

I've found all answers from this question to be incomplete as far as how to use it. This is a more complete answer, written as a utility method:

   suspend fun <T> removeKey(key: Preferences.Key<T>) = withContext(Dispatchers.IO) {
        context.dataStore.edit {
            if (it.contains(key)) {
                it.remove(key)
            }
        }
    }

Upvotes: 0

Tarif Chakder
Tarif Chakder

Reputation: 1846

Use it.

dataStore.edit {
   it.clear()
}

or you can use directly delete file . But I would recommend to use first one

File(
     context.filesDir,
     "datastore/your_datastore_name.preferences_pb"
    ).apply {
       delete()
       createNewFile()
    }

Upvotes: 1

ONVETI
ONVETI

Reputation: 452

in RxDataStore

try this to clear all saved data

    dataStore.updateDataAsync {
            val clear = it.toMutablePreferences().apply {
                this.clear()
            }
            Single.just(clear)
        }

Upvotes: 0

Manohar
Manohar

Reputation: 23384

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()
}

Upvotes: 60

user15136072
user15136072

Reputation:

If you want to delete a specific key then try this

dataStore.edit {
        if (it.contains(key)) {
            it.remove(key)
        }
    } 

Upvotes: 7

Wirling
Wirling

Reputation: 5375

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

context.dataStore.edit {
    it.remove(key)
}

Upvotes: 50

Lev Krasovsky
Lev Krasovsky

Reputation: 71

Try this (for Proto DataStore):

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

Upvotes: 7

Rohit Sathyanarayana
Rohit Sathyanarayana

Reputation: 61

For Proto DataStore you can do:

dataStore.updateData { it.getDefaultInstance() }

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

Upvotes: 1

Related Questions