在Observable中使用'asPromise ()' RxSwift可以在PromiseKit中使用Promise吗?
Use the 'asPromise ()' in the Observable RxSwift can be used in a PromiseKit Promise?
我写函数'asPromise()'
extension PrimitiveSequence {
public func asPromise() -> Promise<Element> {
var disposed: Disposable? = nil
return Promise<Element> { seal in
disposed = self.asObservable()
.subscribe { event in
switch event {
case .next(let element):
seal.fulfill(element)
case .error(let error):
seal.reject(error)
case .completed:
disposed?.dispose()
}
}
}
}}
但是 dispose 很奇怪,我不知道更好。
所以如果你有更好的想法,请告诉我
谢谢
完全没必要去抓一次性的。当 Observable 完成时,它会自动释放所有资源。这是正确的实现:
extension PrimitiveSequence where Trait == SingleTrait { // will only work properly for Singles
public func asPromise() -> Promise<Element> {
Promise<Element> { seal in
_ = subscribe { event in
switch event {
case let .success(element):
seal.fulfill(element)
case let .failure(error):
seal.reject(error)
}
}
}
}
}
您知道 Combine API 已经内置了类似 Promise 的类型吗?
extension PrimitiveSequence where Trait == SingleTrait {
public func asFuture() -> Future<Element, Error> {
Future { fulfill in
_ = self.subscribe(fulfill)
}
}
}
我写函数'asPromise()'
extension PrimitiveSequence {
public func asPromise() -> Promise<Element> {
var disposed: Disposable? = nil
return Promise<Element> { seal in
disposed = self.asObservable()
.subscribe { event in
switch event {
case .next(let element):
seal.fulfill(element)
case .error(let error):
seal.reject(error)
case .completed:
disposed?.dispose()
}
}
}
}}
但是 dispose 很奇怪,我不知道更好。 所以如果你有更好的想法,请告诉我
谢谢
完全没必要去抓一次性的。当 Observable 完成时,它会自动释放所有资源。这是正确的实现:
extension PrimitiveSequence where Trait == SingleTrait { // will only work properly for Singles
public func asPromise() -> Promise<Element> {
Promise<Element> { seal in
_ = subscribe { event in
switch event {
case let .success(element):
seal.fulfill(element)
case let .failure(error):
seal.reject(error)
}
}
}
}
}
您知道 Combine API 已经内置了类似 Promise 的类型吗?
extension PrimitiveSequence where Trait == SingleTrait {
public func asFuture() -> Future<Element, Error> {
Future { fulfill in
_ = self.subscribe(fulfill)
}
}
}