Search code examples
iosbuildrx-swiftflatmap

Instance method 'flatMap' requires that 'String' conform to 'ObservableConvertibleType'


I am getting below build error for RxSwift,

func testFlatMap() {

    let bag = DisposeBag()
    let subject = PublishSubject<String>.init()

    subject.flatMap({ (value) -> String in
            PublishSubject.just(value)
        }).subscribe(

        onNext: { value in
            print(value)
        }

    ).disposed(by: bag)

    subject.on(.next("Test"))
}

Instance method 'flatMap' requires that 'String' conform to 'ObservableConvertibleType'

What am I missing?


Solution

  • This is the problem:

    subject.flatMap({ (value) -> String in
        PublishSubject.just(value)
    })
    

    In the first line you are telling the compiler that the closure returns a String but flatMap requires the closure to return an Observable type.

    Also, FYI: a.flatMap { .just($0) } is effectively a no-op. In other words: aa.flatMap { .just($0) }