Search code examples
swiftreactive-programmingrx-swift

How to convert Maybe to Single without "Sequence doesn't contain any elements"


I am using RxSwift(https://github.com/ReactiveX/RxSwift).

I wrote the following code:

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)

An Error "Sequence doesn't contain any elements" occurred because m1 is Maybe#empty.

How to covert Maybe<String> to Single<String?>?

If Maybe is empty, I'd like to make it nil.

In this case, I want the a variable to be nil.


Solution

  • self resolved

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

    The Document(Comment) say

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

    Custom Extension Version

    custom extension version I think I do not need, but if necessary

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