Home > Software engineering >  Combine's DataTaskPublisher does not output when passed through flatMap in Playgrounds
Combine's DataTaskPublisher does not output when passed through flatMap in Playgrounds

Time:07-28

I created a simple Publisher from an array of paths I want to fetch from the internet. I am setting the failure type to match the DataTaskPublisher, and then I flatMap to get the new Publisher with the DataTask results. However, when I subscribe to the stream with sink, nothing gets called.

Here is my code:

import Combine
import Foundation

class NetworkManager {
    var tasks = Set<AnyCancellable>()
    
    init() {
        getData()
    }
    
    func getData() {
        let baseUrl = URL(string: "https://fmi.unibuc.ro")!
        ["/prezentare", "/cazare"].publisher
            .setFailureType(to: URLError.self)
            .flatMap { path -> URLSession.DataTaskPublisher in
                let url = baseUrl.appendingPathComponent(path)
                return URLSession.shared.dataTaskPublisher(for: url)
            }
            .sink(receiveCompletion: { completion in
                print(completion)
            }, receiveValue: { value in
                print(value)
            })
            .store(in: &tasks)
    }
}

let manager = NetworkManager()

What am I doing wrong?

  • Related