Kotlin firebase executed with addOnSuccessListener even if fails

216 Views Asked by At

I have this piece of code and it is executed with .continueWith and addOnSuccessListener even if failed.I try with continueWithTask but i dont understand very well Tasks API. Please help me to understand how to do this.

db.collection(customGameName).document().get().continueWith {
    if (!gameslist.contains(customGameName)) {
        gameslist.add(customGameName)
        SavedPreference.setGamesList(this, gameslist)
        adapter.notifyDataSetChanged()
    }else{
        Toast.makeText(this,"$customGameName is in the list already!",Toast.LENGTH_SHORT).show()
    }
}.addOnFailureListener {
    Toast.makeText(this,"$customGameName not exist!",Toast.LENGTH_SHORT).show()
    gameslist.remove(customGameName)
    SavedPreference.setGamesList(this, gameslist)
    adapter.notifyDataSetChanged()
}
1

There are 1 best solutions below

0
Frank van Puffelen On

If you have code that you only want to run when the task is successful, add a success listener to the task. That should look something like this:

db.collection(customGameName).document().get()
.addOnSuccessListener { document ->
    if (document != null) {
        Log.d(TAG, "DocumentSnapshot data: ${document.data}")
        if (!gameslist.contains(customGameName)) {
            gameslist.add(customGameName)
            SavedPreference.setGamesList(this, gameslist)
            adapter.notifyDataSetChanged()
        }else{
            Toast.makeText(this,"$customGameName is in the list already!",Toast.LENGTH_SHORT).show()
        }
    } else {
        Log.d(TAG, "No such document")
    }
}.addOnFailureListener {
    Toast.makeText(this,"$customGameName not exist!",Toast.LENGTH_SHORT).show()
    gameslist.remove(customGameName)
    SavedPreference.setGamesList(this, gameslist)
    adapter.notifyDataSetChanged()
}

Note that this code is pretty much straight from the Firebase documentation on getting a document in Kotlin, so I recommend spending some more time there.