0

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()
            
        }
    }
dubbeat
  • 7,706
  • 18
  • 70
  • 122
  • Just to be sure, you want to forward any event from the observable returned by your method to the `PublishSubject` ? – Morniak Apr 26 '22 at 13:17
  • So what I want is everytime my publish subject emits an onNext event I want to trigger the observable of 'myMethod' – dubbeat Apr 26 '22 at 13:19

2 Answers2

1

First, the bind(to:) method is in the RxCocoa Framework so you need to add import RxCocoa in your file.

Then, the observable created by myMethod will only be able to emit the event from the .create block. You can't use bind on it. If you need an observable with both the events from your subject and from the myMethod observable, you can do that :

let thirdObservable = Observable.merge(publish, myMethod())
Morniak
  • 958
  • 1
  • 12
  • 37
1

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.

Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • Thanks for this. I think the thing was that I couldnt bind(to:) and had to use bind(onNext:) when attempting to bind from a publishSubject – dubbeat Apr 26 '22 at 18:01
  • 1
    Either there is a lot you are leaving out or you aren't understanding something. The way `MyMethod()` is written, calling `bind(onNext: { myMethod() ))` will do nothing. It's a no-op. – Daniel T. Apr 26 '22 at 18:05