반응형
안녕하세요 코찐입니다.
아래의 자료를 따라서 공부하고 있습니다.
https://www.raywenderlich.com/books/combine-asynchronous-programming-with-swift/v2.0
리소스 관리하는 Publisher 들인데, API 작업할 때 유용하게 사용할 수 있습니다.
share
value 타입이 아닌 reference 타입의 publisher를 공유할 수 있도록 해줍니다.
주의할 점은 이미 complete 된 share publisher를 구독하면 complete만 받게 됩니다.
let shared = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.raywenderlich.com")!)
.map(\.data)
.print("shared")
.share()
print("subscribing first")
let subscription1 = shared.sink(
receiveCompletion: { _ in },
receiveValue: { print("subscription1 received: '\($0)'") }
)
print("subscribing second")
let subscription2 = shared.sink(
receiveCompletion: { _ in },
receiveValue: { print("subscription2 received: '\($0)'") }
)
subscribing first
shared: receive subscription: (DataTaskPublisher)
shared: request unlimited
subscribing second
shared: receive value: (275400 bytes)
subscription1 received: '275400 bytes'
subscription2 received: '275400 bytes'
shared: receive finished
multicast
connect()를 호출해야 이벤트를 시작합니다.
그래서 subscription을 다 만들어두고, connect 할 수 있어서 편합니다.
let subject = PassthroughSubject<Data, URLError>()
let multicasted = URLSession.shared
.dataTaskPublisher(for: URL(string: "https://www.raywenderlich.com")!)
.map(\.data)
.print("multicast")
.multicast(subject: subject)
// 3
let subscription1 = multicasted
.sink(
receiveCompletion: { _ in },
receiveValue: { print("subscription1 received: '\($0)'") }
)
let subscription2 = multicasted
.sink(
receiveCompletion: { _ in },
receiveValue: { print("subscription2 received: '\($0)'") }
)
let cancellable = multicasted.connect()
multicast: receive subscription: (DataTaskPublisher)
multicast: request unlimited
multicast: receive value: (275400 bytes)
subscription1 received: '275400 bytes'
subscription2 received: '275400 bytes'
multicast: receive finished
future
future는 클로저 안의 동작을 즉시 실행합니다.
그리고 구독하면 그 값을 전달합니다.
func performSomeWork() throws -> Int {
print("Performing some work and returning a result")
return 5
}
let future = Future<Int, Error> { fulfill in
do {
let result = try performSomeWork()
fulfill(.success(result))
} catch {
fulfill(.failure(error))
}
}
print("Subscribing to future...")
let subscription1 = future
.sink(
receiveCompletion: { _ in print("subscription1 completed") },
receiveValue: { print("subscription1 received: '\($0)'") }
)
let subscription2 = future
.sink(
receiveCompletion: { _ in print("subscription2 completed") },
receiveValue: { print("subscription2 received: '\($0)'") }
)
Performing some work and returning a result
Subscribing to future...
subscription1 received: '5'
subscription1 completed
subscription2 received: '5'
subscription2 completed
반응형
'iOS > Combine' 카테고리의 다른 글
[Combine] Chapter 17: Schedulers (0) | 2021.02.03 |
---|---|
[Combine] Chapter 16: Error Handling (0) | 2021.02.01 |
[Combine 책 정리] Chapter 12: Key-Value Observing (0) | 2021.01.27 |
[Combine 책 정리] Chapter 11: Timers (0) | 2021.01.27 |
[Combine 책 정리] Chapter 10: Debugging (0) | 2021.01.27 |