Search code examples
for-loopiterationrx-swift

Iterating over and adding to an array in RxSwift


I am making a network request from which I am getting a bunch of users, I am also given a emailDetails object that holds the userId property as well. I am trying to iterate over the users coming from the network request to match up all of the userIds from the emailDetails

I am not sure how to iterate, I know enumerated exists in RxSwift.

self.emailRecipients = networkRequestToGetUser
            .asObservable()
            .map { users in users.filter {$0.userId == 
             emailDetails.userIds }.first }
            .map {correctUsers in return correctUsers?.email}
            .unwrap()

Error I'm getting: Binary operator '==' cannot be applied to operands of type 'String' and '[String]'


Solution

  • as far as I understand your code snippet, your issue is not actually related to RxSwift. Apparently emailDetails.userIds is an Array of Strings [String]. You could check if the Array contains the userId using this as you mapping instead:

        .map { users in users.filter { emailDetails.userIds.contains($0.userId) }.first }
    

    to get the first match. If you want all of them in an Array, just drop the .first and map to the email field:

    self.emailRecipients = networkRequestToGetUser
            .asObservable()
            .map { users in 
                users.filter {
                    emailDetails.userIds.contains($0.userId)
                }.map { $0.email } 
            }
    

    to get a Observable of an Array of email addresses. To get the actual adresses, don't forget to subscribe() to that emailRecipients-Observable.