Open Taehyeon-Kim opened 10 months ago
share()
multicast()
import Foundation import Combine let numbers = [1,2,3,4,5,6,7,8,9,10] .publisher .print() var cancellabes = Set<AnyCancellable>() numbers.sink { _ in }.store(in: &cancellabes) numbers.sink { _ in }.store(in: &cancellabes)
receive subscription: ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) request unlimited receive value: (1) receive value: (2) receive value: (3) receive value: (4) receive value: (5) receive value: (6) receive value: (7) receive value: (8) receive value: (9) receive value: (10) receive finished receive subscription: ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) request unlimited receive value: (1) receive value: (2) receive value: (3) receive value: (4) receive value: (5) receive value: (6) receive value: (7) receive value: (8) receive value: (9) receive value: (10) receive finished
struct Post: Decodable { let userId: Int let id: Int let title: String // let body: String } let url = URL(string: "https://jsonplaceholder.typicode.com/posts")! let posts = URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .decode(type: [Post].self, decoder: JSONDecoder()) .replaceError(with: []) .print() .share() posts .sink(receiveValue: { print("subscription1 value: \($0)") }) .store(in: &cancellables) posts .sink(receiveValue: { print("subscription2 value: \($0)") }) .store(in: &cancellables)
let postsSubject = PassthroughSubject<[Post], Never>() let url = URL(string: "https://jsonplaceholder.typicode.com/posts")! let posts = URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .decode(type: [Post].self, decoder: JSONDecoder()) .replaceError(with: []) .print() .multicast(subject: postsSubject)
posts.connect().store(in: &cancellables)
해당 메서드를 사용하면 연결 가능한 래퍼를 생성할 수 있다. Subject를 다룰 필요 없이 즉시 퍼블리셔를 ConnectablePublisher로 전환할 수 있다.
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")! let posts = URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .decode(type: [Post].self, decoder: JSONDecoder()) .replaceError(with: []) .print() .makeConnectable() posts.connect().store(in: &cancellables)
let cancellable = Timer.publish(every: 1, on: .main, in: .default) .autoconnect() .sink() { date in print ("Date now: \(date)") }
문제 의식
Combine
share operator
multicast operator
Advantages
makeConnectable()
해당 메서드를 사용하면 연결 가능한 래퍼를 생성할 수 있다. Subject를 다룰 필요 없이 즉시 퍼블리셔를 ConnectablePublisher로 전환할 수 있다.
autoconnect operator
정리
Links: