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

>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()

Leave a Reply