📱 iOS, Swift/📚 Combine
3. Transforming Operators
itllbegone
2023. 4. 23. 17:00
Getting started
Operators Are publishers
여기서는 에러핸들링에 대한 내용 보다는 operator를 이용한 스트림의 변화에 대해 알아볼것이다~
Collecting values
.collect()
스트림을 모두 모아 하나의 array 로 반환합니다
💡 주의: 다른 counting or limit이 없는 buffering operators와 같이 사용할 경우 collect에 값을 계속 담게되어 이벤트가 방출하지 않아 메모리 누수가 일어날 수 있음
Mapping values
.map(_:)
발생하는 이벤트를 각각 매핑하여 다른 형태로 변환
.tryMap(_:)
try가 가능한 .map(_:)
try 문이 실패 시 스트림의 Error에 해당하는 failure(Error) 이벤트를 방출하고 스트림을 종료한다
example(of: "tryMap") {
// 1
Just("Directory name that does not exist")
// 2
.tryMap { try FileManager.default.contentsOfDirectory(atPath: $0) }
// 3
.sink(receiveCompletion: { print($0) },
receiveValue: { print($0) })
.store(in: &subscriptions)
}
// Result
——— Example of: tryMap ———
failure(..."The folder “Directory name that does not exist” doesn't exist."...)
Flattening publishers
.flatMap(maxPublisher:_:)
발생하는 여러 이벤트를 새로운 하나의 publisher로 매핑하여 이를 구독할 수 있도록 변환시켜줌
스트림 평면화! 여러 스트림 이벤트를 받아 하나의 스트림으로(1차원으로) 평면화 시켜줌
Replacing upstream output
replaceNil(with:)
optional 이벤트에 대해 값이 있다면 일반 값을, nil이라면 대체값을 방출함
Optional(value) ?? DefaultValue 와 동일한 효과를 가짐
replaceEmpty(with:)
Empty(completeImmediately: true) 에 대한 이벤트를 받았을 때 대체값을 방출함
이 때 (completeImmediately: false) 인 경우에는 replaceEmpty 스트림이 발생하지 않음
Incrementally transforming output
scan(_:_:)
reduce(_:_:) 와 유사하나, 각각의 모든 값들에 대한 이벤트를 방출한다
scan은 각각의 연산 결과를 이벤트로!
reduce는 연산 결과의 총합을 이벤트로!