如何在没有“序列不包含任何元素”的情况下将Maybe转换为Single

时间:2019-08-02 15:21:45

标签: swift reactive-programming rx-swift

我使用RxSwift(https://github.com/ReactiveX/RxSwift

我这样写

m1

因为Maybe#emptyMaybe<String>,所以出现“序列不包含任何元素”的情况。

如何将Single<String?>转换为nil

如果Maybeempty,则希望为a

在这种情况下,我希望nil变量为{{1}}。

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.
 */

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

自定义扩展版本

我认为不需要自定义扩展版本, 但如有必要

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