Swift: Swift combine with sync


import UIKit
import Combine
public func example(of: String, execute: () -> Void) {
print("------ (of) ------")
execute()
}
example(of: "URLSession+Publisher") {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }

let _ = URLSession.shared
.dataTaskPublisher(for: url)
.sink(receiveCompletion: { completion in
if case .failure(let error) = completion {
print("Failed with error (error)")
} else {
print("Success") 
}
}, receiveValue: { data, response in
print("Data retrieved with size (data.count), response = (response)")
})
}

这段代码在sync中不打印任何东西。我试着通过playground运行它,我的xcode版本是12.5.1

试试这个:

import Combine
import PlaygroundSupport
import UIKit
public func example(of: String, execute: () -> Void) {
print("------ (of) ------")
execute()
}
var cancellable: Cancellable?
example(of: "URLSession+Publisher") {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else { return }
cancellable = URLSession.shared
.dataTaskPublisher(for: url)
.sink(receiveCompletion: { completion in
if case .failure(let error) = completion {
print("Failed with error (error)")
} else {
print("Success")
}
}, receiveValue: { data, response in
print("Data retrieved with size (data.count), response = (response)")
})
}
PlaygroundPage.current.needsIndefiniteExecution = true

您需要告诉playground页面在最后一行代码之后继续运行,以便它可以等待服务器响应,并且您需要存储可取消的。

最新更新