swift - RxSwift unwrap optional handy function? -


currently have created function unwrapoptional safely unwrap optional input in stream.

    func unwrapoptional<t>(x: optional<t>) -> observable<t> {        return x.map(observable.just) ?? observable.empty()     }      let aopt: string? = "aopt"     _ = observable.of(aopt).flatmap(unwrapoptional).subscribenext { x in print(x)}      let anil: string? = nil     _ = observable.of(anil).flatmap(unwrapoptional).subscribenext { x in print(x)}      let a: string = "a"     _ = observable.of(a).flatmap(unwrapoptional).subscribenext { x in print(x)}     // output      aopt     

what want archive create handy function instead of using flatmap(unwrapoptional), example

observable.of(a).unwrapoptional() 

something tried do, never compiles...

extension observabletype {     func unwrapoptional<o : observableconvertibletype>() -> rxswift.observable<o.e> {         return self.flatmap(unwrapoptional)     } } 

you want unwrapoptional method work on observables have optional type.

so somehow have constraint element of observable conform optional protocol.

extension observable element: optionaltype {     /// returns observable nil values original observable     /// skipped     func unwrappedoptional() -> observable<element.wrapped> {         return self.filter { $0.asoptional != nil }.map { $0.asoptional! }     } } 

unfortunately, swift not define such protocol (optionaltype). need define yourself

/// represent optional value /// /// needed restrict our observable extension observable generate /// .next events optional payload protocol optionaltype {     associatedtype wrapped     var asoptional:  wrapped? { } }  /// implementation of optionaltype protocol optional type extension optional: optionaltype {     var asoptional: wrapped? { return self } } 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -