简体   繁体   English

URLSession.shared.dataTask vs dataTaskPublisher,什么时候用?

[英]URLSession.shared.dataTask vs dataTaskPublisher, when to use which?

I recently encounter two data fetching (download) API that performs seemingly the same thing to me.我最近遇到了两个数据获取(下载)API,它们对我执行看似相同的事情。 I cannot see when should I use one over the other.我不知道什么时候应该使用一个而不是另一个。

I can use URLSession.shared.dataTask我可以使用URLSession.shared.dataTask

    var tasks: [URLSessionDataTask] = []

    func loadItems(tuple : (name : String, imageURL : URL)) {
        let task = URLSession.shared.dataTask(with: tuple.imageURL, completionHandler :
        { data, response, error in
            guard let data = data, error == nil else { return }
            DispatchQueue.main.async() { [weak self] in
                self?.displayFlag(data: data, title: tuple.name)
            }
        })
        tasks.append(task)
        task.resume()
    }

    deinit {
        tasks.forEach {
            $0.cancel()
        }
    }

Or I can use URLSession.shared.dataTaskPublisher或者我可以使用URLSession.shared.dataTaskPublisher

    var cancellables: [AnyCancellable] = []

    func loadItems(tuple : (name : String, imageURL : URL)) {
        URLSession.shared.dataTaskPublisher(for: tuple.imageURL)
            .sink(
                receiveCompletion: {
                    completion in
                    switch completion {
                    case .finished:
                        break
                    case .failure( _):
                        return
                    }},
                receiveValue: { data, _ in DispatchQueue.main.async { [weak self] in self?.displayFlag(data: data, title: tuple.name) } })
            .store(in: &cancellables)
    }

    deinit {
        cancellables.forEach {
            $0.cancel()
        }
    }

I don't see their distinct differences, as both also can fetch, and both also provide us the ability to cancel the tasks easily.我没有看到它们的明显区别,因为两者都可以获取,并且都为我们提供了轻松取消任务的能力。 Can someone shed some light on their differences in terms of when to use which?有人可以阐明他们在何时使用哪个方面的差异吗?

The first one is the classic.第一个是经典。 It has been present for quite some time now and most if not all developers are familiar with it.它已经存在了很长一段时间,并且大多数(如果不是全部)开发人员都熟悉它。

The second is a wrapper around the first one and allows combining it with other publishers (eg Perform some request only when first two requests were performed).第二个是第一个的包装器,并允许将其与其他发布者组合(例如,仅在执行前两个请求时才执行某些请求)。 Combination of data tasks using the first approach would be far more difficult.使用第一种方法组合数据任务要困难得多。

So in a gist: use first one for one-shot requests.所以在一个要点中:将第一个用于一次性请求。 Use second one when more logic is needed to combine/pass results with/to other publishers (not only from URLSession).当需要更多逻辑来将结果与/传递给其他发布者(不仅来自 URLSession)时,请使用第二个。 This is, basically, the idea behind Combine framework - you can combine different ways of async mechanisms (datatasks utilising callbacks being one of them).这基本上是Combine 框架背后的想法——您可以组合不同方式的异步机制(利用回调的数据任务就是其中之一)。

More info can be found in last year's WWDC video on introducing combine.更多信息可以在去年的 WWDC 视频中找到,介绍联合收割机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM