0x6d6e
0x6d6e

Reputation: 153

RxSwift Subscribing on ControlEvent

The first observable fires, but the second does not. What gives? I switched the events in the block i.e print($0) in the second bloack and vice-versa, then the first does not work, but the second works. What is it about $0 versus a regular string that makes the observable observe?

      let someObservable  = self.inputButton!.rx.tap.subscribe(){
        print($0)
      }

      let someObservable1 = self.inputButton!.rx.tap.subscribe(){
        print("Hello")
      }

Upvotes: 2

Views: 4662

Answers (1)

iska
iska

Reputation: 2248

In the first one, you are using the $0, which is the first argument that is passed to the closure that you've provided.

let someObservable  = self.inputButton!.rx.tap.subscribe(){
    print($0)
}

In this case the compiler decides that you are actually calling the following function, because it matches that what you are using, i.e. it expects one nameless argument, which in turn is a closure with one argument, the event:

func subscribe(_ on: @escaping (Event<E>) -> Void)

You can rewrite your first code like this:

let someObservable  = self.inputButton!.rx.tap.subscribe() { event in
   print(event)
}

Now, in the second one you are providing a closure, that doesn't use any passed arguments. So the compiler has to find another function that would be syntactically valid at this point. As a matter of fact it will use this one for you:

func subscribe(file: String = #file, line: UInt = #line, function: String = #function, onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil)

All of this function's arguments have default values and you can ignore all of them. The last argument onDispose is of closure type and can be written with the trailing closure notation. That means that the closure that you pass here:

  let someObservable1 = self.inputButton!.rx.tap.subscribe(){
      print("Hello")
  }

will be used as your dispose block.


Rule of thumb when using RxSwift: Be explicit, name your arguments, provide the types of your arguments, in the long run you will spare a lot more time!

Upvotes: 4

Related Questions