Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine's DataTaskPublisher does not output when passed through flatMap in Playgrounds

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? 🤔

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Swift playgrounds finish execution when all synchronous code in them returned. However, you are executing a network request asynchronously, so you need to tell the playground to wait for the async result.

Call this before starting the network request:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

And in the sink, you can finish execution by calling

PlaygroundPage.current.finishExecution()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading