How to apply .filter operator on individual elements of a CurrentValueSubject that's an array in Swift Combine?

Viewed 1240

I have a CurrentValueSubject that's an array of ChatModelFirebase. What I want to do is remove all ChatModelFirebase models that have a status field of "canceled". The issue is that when I apply .filter(..) operator it's acting on the entire array and not the individual items.

var chatFirebaseModels: CurrentValueSubject<[ChatModelFirebase], Never> = CurrentValueSubject([])

chatFirebaseModels
    .filter({ (chatModelFireBaseArray) -> Bool in
        // I want individual array items, not chatModelFireBaseArray
        return false
    })

Here is what code completion looks like:

enter image description here

You can see that .filter(..) is being applied to the [ChatModelFirebase] array and not the individual ChatModelFirebase models.

Is the answer here to just use .flatMap(..)? I am curious if there is a right way of using .filter(...), hence my question.

1 Answers

You can either use .map to return a filtered array:

chatFirebaseModels
    .map { array in
       array.filter { element in
          // ... filter by element
       }
    }

Or use a pure-Combine chain (though, seems unnecessarily complicated):

chatFirebaseModels
   .flatMap { Publishers.Sequence(sequence: $0) }
   .filter { element in
      // ... filter by element
   }
   .collect()
Related