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
.
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.
*/
custom extension version I think I do not need, but if necessary
extension Maybe {
func asOptionalElementSingle() -> Single<Element?> {
return self.asObservable().first()
}
}