Rxswift: Request: Observable creation from Optional

Created on 7 Sep 2016  路  9Comments  路  Source: ReactiveX/RxSwift

I request extension of Optional like Array.toObservable.
https://github.com/ReactiveX/RxSwift/blob/master/RxSwift/Observables/Observable%2BCreation.swift#L200-L213
Optional is same of Array that has 1 element or empty. (It would be similar in Array.flatMap)
So, I think we can create Optional.toObservable also.

I think this feature is useful, and has many profit.

The most simple example is:

var a: Observable<Int?>
a.flatMap { $0.toObservable() } // -> Observable<Int>

Most helpful comment

Hi @tarunon ,

I'm ~50:50 on this. I understand reasons for pro and con. For the interface to be consistent with 3.0.0 version we would need to have it as Observable.from(optional).

If somebody needs this please tumb up this issue, or thumb down it. For this one, I'm fine with either outcome.

All 9 comments

Hi @tarunon ,

I believe there is already https://github.com/RxSwiftCommunity/RxOptional .

Hi @kzaher san,

Yes, I believed it also, but I could not find Optional.toObservable in RxOptional.
I opened this issue, because I think this feature would be needed standard support more than adding in RxOptional.

Hi guys, Isn't it filterNil in RxOptional?

@sergdort
Thank you for help.
Yes, I think .filterNil() is equal to .flatMap { $0.toObservable() }, and Observable.just(optional).filterNil() is equal to optional.toObservable() also.
This feature is like of monad transform.

Hi @tarunon ,

I'm ~50:50 on this. I understand reasons for pro and con. For the interface to be consistent with 3.0.0 version we would need to have it as Observable.from(optional).

If somebody needs this please tumb up this issue, or thumb down it. For this one, I'm fine with either outcome.

this is my solution, i made a set of methods to write the bindings with that syntax but you can see here how i fixed it:

infix operator ~>
@discardableResult
public func ~> <T>(variable: Variable<T>, property: AnyObserver<T?>) -> Disposable {
    let bindDisposable = variable.asObservable()
        .map { $0 }
        .bindTo(property)
    return bindDisposable
}

and just use it like

var a: Observable<String?>
var label = UILabel()
(a ~> label).addDisposableTo(disposableBag) // this is the Disposable

Hi @Busta117 ,
I think your solution is near that convert Observable<T> to Observable<T?>.
This request is about transform Optional<T> to Observable<T>.

Hi @tarunon ,

I would be fine adding Observable.from with optional overload. I think we could include this for 3.2.

Would you like try to give it a try yourself?

Hi @kzaher ,
Of course! I try to make PR 馃榿
Thank you notification.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hannesstruss picture hannesstruss  路  3Comments

trant picture trant  路  3Comments

RobinFalko picture RobinFalko  路  3Comments

angerman picture angerman  路  3Comments

apoloa picture apoloa  路  3Comments