Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter array of Observable element | RxSwift

I have a struct Person and person array as following

struct Person {
  let name : String
  let age : Int
}

let personArray = [
    Person(name : "Max", age : 32),
    Person(name : "Jones", age : 42),
    Person(name : "Other", age : 62)
]

I create an observable sequence as following

let seq = Observable.just(personArray)

now How can I filter this array by relevant person name ?

e.g. I want an observable sequence that contains person name that starts with 'M'

how to do this ??

like image 617
Mahabub Avatar asked Feb 11 '17 17:02

Mahabub


2 Answers

Try this:

let seq = Observable.just(personArray)


seq.just(personArray)
   .map{
       $0.filter{ $0.name.hasPrefix("M")}
   }
   .subscribe(onNext: { item in
       print(item)
   })

You also could do this:

let seq = Observable.just(personArray.filter{ $0.name.hasPrefix("M") })
like image 130
xandrefreire Avatar answered Sep 19 '22 13:09

xandrefreire


Here is a simple playground example that I used to prototype the same problem:

import RxSwift

let dataSource = Observable.just([1, 2, 3, 4, 5])
let filterSource = PublishSubject<Int>()

Observable
    .combineLatest(dataSource, filterSource) { data, filter in data.filter { $0 != filter } }
    .subscribe(onNext: { print($0) })

filterSource.onNext(3)
filterSource.onNext(2)

print("Done")

This prints:

[1, 2, 4, 5]
[1, 3, 4, 5]
Done
like image 32
Chris Conover Avatar answered Sep 19 '22 13:09

Chris Conover