OpenCombine 用于 JavaScriptKit/WebAssembly API 的助手库。目前提供:
Scheduler
协议的 JSScheduler
类。 这允许你在浏览器环境中使用时间相关的 Combine 操作符,例如 measureInterval
、debounce
、throttle
和 timeout
。JSValueDecoder
上实现了 TopLevelDecoder
。JSPromise
上有一个 publisher
属性,它可以将你的 JavaScript Promise
实例转换为 Combine 发布者。这是一个定时器的示例,它每秒从远程服务器获取一个 UUID,使用 JSValueDecoder
解析它,然后将结果显示为文本。
import JavaScriptKit
import OpenCombine
import OpenCombineJS
private let jsFetch = JSObject.global.fetch.function!
func fetch(_ url: String) -> JSPromise {
JSPromise(jsFetch(url).object!)!
}
let document = JSObject.global.document
var p = document.createElement("p")
_ = document.body.appendChild(p)
var subscription: AnyCancellable?
let timer = JSTimer(millisecondsDelay: 1000, isRepeating: true) {
subscription = fetch("https://httpbin.org/uuid")
.publisher
.flatMap {
JSPromise($0.json().object!)!.publisher
}
.mapError { $0 as Error }
.map { Result<String, Error>.success($0.uuid.string!) }
.catch { Just(.failure($0)) }
.sink {
let time = JSDate().toLocaleTimeString()
switch $0 {
case let .success(uuid):
p.innerText = .string("At \(time) received uuid \(uuid)")
case let .failure(error):
p.innerText = .string("At \(time) received error \(error)")
}
}
}
本项目遵守贡献者盟约行为准则。 参与本项目,即表示您需要遵守该准则。 如有不可接受的行为,请发送邮件至 hello@swiftwasm.org 进行举报。