我使用RxSwift(https://github.com/ReactiveX/RxSwift)
m1
因为Maybe#empty
是Maybe<String>
,所以出现“序列不包含任何元素”的情况。
如何将Single<String?>
转换为nil
。
如果Maybe
为empty
,则希望为a
。
在这种情况下,我希望nil
变量为{{1}}。
答案 0 :(得分:1)
let 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.
*/
我认为不需要自定义扩展版本, 但如有必要
extension Maybe {
func asOptionalElementSingle() -> Single<Element?> {
return self.asObservable().first()
}
}