Home > Software design >  Kotlin: How to check if field's value is in Array or not in FireStore
Kotlin: How to check if field's value is in Array or not in FireStore

Time:02-01

enter image description here

I have below fireStore structure. It has diary collection and users collection.

When I draw data from diary collection in my App, I want to check two things.

  1. If this diary is blocked by logged-in user or not.
  2. If this diary user is blocked by logged-in user or not.

So I will user diaryId of diary collection for 1st, and userId of diary collection for 2nd.

My idea is users collection will have blockedDiary ArrayField and blockedUser ArrayField.

And in App I will run users collection first and then run diary collection as using whereNotIn to compare diaryId exists in blockedDiary or userId exists in blockedUser.

        userDB.document("$userId")
            .get()
            .addOnSuccessListener { document ->
                var blockedUser = document.data?.getValue("blockedUser") as ArrayList<String>
                var blockedDiary = document.data?.getValue("blockedDiary") as ArrayList<String>

                diaryDB
                    .whereNotIn("diaryId", blockedDiary)
                    .whereNotIn("userId", blockedUser)
                    .get()
                    .addOnSuccessListener { documents ->

But this throws error A non-empty array is required for 'not_in' filters..

Because I set default array of blockedUser and blockedDiary as empty array [] since some user doesn't block any diary or user.

How can I compare with empty array ?

Or is there any good way to implement my purpose other than this way?

CodePudding user response:

var blockedUser = document.data?.getValue("blockedUser") as ArrayList<String>
var blockedDiary = document.data?.getValue("blockedDiary") as ArrayList<String>

in above lines of code , you are having blockedUser and blockedDiary as an arraylist then you can simply use it's method isNullOrEmpty() which will return true in case when arraylist variable is null or empty so you can do code something like this

var storeBuilder:MentionReturnTypeOfWhereNotIn ? = null
if(blockedDiary.isNullOrEmpty().not()){
             storeBuilder = diaryDB
                    .whereNotIn("diaryId", blockedDiary)
}

if(blockedUser.isNullOrEmpty().not(){
   if(storeBuilder == null){
     storeBuilder = diaryDB.whereNotIn("userId", blockedUser)
   }else{
     storeBuilder = storeBuilder.whereNotIn("userId", blockedUser)
   }
}
                   
var tmp = if(storeBuilder == null) diaryDB else storeBuilder
 
                    tmp.get()
                    .addOnSuccessListener { documents ->

You may need to manage about conditions as i just tried to optimise code but sure about isNullOrEmpty method

  • Related