What is flatMap operator in Swift Combine?
FlatMap operator is used when you want to convert specific data type to Publisher.
Let's look at one example code
import UIKit
import Combine
struct PostQuery {
let id: String
}
struct Post: Decodable {
let id: Int
let title: String
let body: String
}
//Subject to publish data type of PostQuery
var blogPublisher = PassthroughSubject<PostQuery, URLError>()
var cancellable: AnyCancellable!
var cancellables = Set<AnyCancellable>()
//Convert PostQuery type data to URLSession.Data.Publisher type data
let publisher = blogPublisher.flatMap(maxPublishers: .unlimited, { query -> URLSession.DataTaskPublisher in
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/\(query.id)")!
return URLSession.shared.dataTaskPublisher(for: url)
}).eraseToAnyPublisher()
publisher.map {
$0.data
}
.decode(type: Post.self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("finished")
case .failure(let error):
print(error)
}
}, receiveValue: { output in
print(output)
})
.store(in: &cancellables)
blogPublisher.send(PostQuery(id: "1"))
blogPublisher.send(PostQuery(id: "2"))
blogPublisher.send(completion: .finished)
The result of above code is
Post(id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto")
Post(id: 2, title: "qui est esse", body: "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla")
finished
댓글 없음:
댓글 쓰기