Search code examples
rx-swift

How Can I use the Bind Method in RXSwift?


The following sample code throws an error stating

No exact matches in call to instance method 'bind'

How can I bind the onNext of my publish subject to my observable?

let publish = PublishSubject<Void>()
// Error Here
publish.bind(to: myMethod())

func myMethod() -> Observable<Void> {
        return Observable.create{ observer in
            observer.onNext(())
            observer.onCompleted()
            
            return Disposables.create()
            
        }
    }

Solution

  • So what I want is everytime my publish subject emits an onNext event I want to trigger the observable of 'myMethod'

    I'm not sure how to interpret this, but it sounds like you want something like:

    let publish = PublishSubject<Void>()
    let response = publish.flatMap { myMethod() }
    response
        .bind(onNext: { print($0) })
    
    func myMethod() -> Observable<Void> {
        Observable.create{ observer in
            observer.onNext(())
            observer.onCompleted()
            return Disposables.create()
        }
    }
    

    But it all seems rather pointless since all myMethod() does is emit a next event.