이니셜라이저는 두 개의 인자를 받는다.
조건에 맞는 요소만 남기고 싶을 때 사용할 수 있다.
// Publishers.Filter Publisher
Publishers.Filter(upstream: Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3, 4])) { $0.isMultiple(of: 2) }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Filter Error")
case .finished:
print("Combine Filter Finish")
}
}, receiveValue: { value in
print("Combine Filter : \(value)")
})
.store(in: &cancellables)
// filter Operator
Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3, 4])
.filter { $0.isMultiple(of: 2) }
.sink(receiveCompletion: { completion in
switch completion {
case .failure:
print("Combine Filter Error")
case .finished:
print("Combine Filter Finish")
}
}, receiveValue: { value in
print("Combine Filter : \(value)")
})
.store(in: &cancellables)
// Combine Filter : 2
// Combine Filter : 4
// Combine Filter Finish
결과적으로 1, 2, 3, 4의 값에서 2, 4의 값만 다시 발행된다.
Observable.from([1, 2, 3, 4])
.filter { $0.isMultiple(of: 2) }
.subscribe(onNext: { value in
print("RxSwift Filter : \(value)")
}, onError: { _ in
print("RxSwift Filter Error")
}, onCompleted: {
print("RxSwift Filter Finish")
})
.disposed(by: disposeBag)
// RxSwift Filter : 2
// RxSwift Filter : 4
// RxSwift Filter Finish
SignalProducer([1, 2, 3, 4])
.filter { $0.isMultiple(of: 2) }
.start { event in
switch event {
case let .value(value):
print("ReactiveSwift Filter : \(value)")
case .failed:
print("ReactiveSwift Filter")
case .completed:
print("ReactiveSwift Filter")
default:
break
}
}
// ReactiveSwift Filter : 2
// ReactiveSwift Filter : 4
// ReactiveSwift Filter Finish