gpt4 book ai didi

swift - 如何在没有 "Sequence doesn' t 包含任何元素的情况下将 Maybe 转换为 Single"

转载 作者:行者123 更新时间:2023-11-28 05:39:33 25 4
gpt4 key购买 nike

我正在使用 RxSwift(https://github.com/ReactiveX/RxSwift)。

我写了下面的代码:

let m1 = Maybe<String>.empty()
let m2 = Maybe<String>.just("AA")

let s1 = m1.asObservable().asSingle()
let s2 = m2.asObservable().asSingle()


Single.zip(s1, s2).subscribe(onSuccess: { a, b in
print("==================")
print(a)
print(b)
print("==================")
}, onError: { e in
print("EEEEE")
print(e) // Sequence doesn't contain any elements.
}).disposed(by: disposeBag)

一个错误 "Sequence doesn't contain any elements"发生是因为m1Maybe#empty .

如何隐藏Maybe<String>Single<String?>

如果Maybeempty , 我想做 nil.

在这种情况下,我想要 a变量为 nil .

最佳答案

自行解决

让 s1 = m1.asObservable().first()

文档(评论)说

/**
The `first` operator emits only the very first item emitted by this Observable,
or nil if this Observable completes without emitting anything.

- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)

- returns: An observable sequence that emits a single element or nil if the source observable sequence completes without emitting any items.
*/

https://github.com/ReactiveX/RxSwift/blob/c6c0c540109678b96639c25e9c0ebe4a6d7a69a9/RxSwift/Traits/ObservableType%2BPrimitiveSequence.swift#L30

自定义扩展版本

自定义扩展版本我觉得我不需要,但如果有必要

extension Maybe {
func asOptionalElementSingle() -> Single<Element?> {
return self.asObservable().first()
}
}

关于swift - 如何在没有 "Sequence doesn' t 包含任何元素的情况下将 Maybe 转换为 Single",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com