0

I'm using the io.reactivex.rxkotlin extension function:

fun <T : Any> Observable<T>.subscribeBy(
        onError: (Throwable) -> Unit = onErrorStub,
        onComplete: () -> Unit = onCompleteStub,
        onNext: (T) -> Unit = onNextStub
        ): Disposable

And when I use this extension there is a difference if I choose to send a parameter or if I use lambda. For example

first implementation:

myObservable.subscribeBy { str ->
    // onNext
}

Second implementation:

myObservable.subscribeBy({ throwable ->
    // onError
})
  • in the first implementation the function is the onNext
  • and in the second implementation the function is the onError

And I'm not sure why.

CookieMonster
  • 1,723
  • 1
  • 15
  • 15

2 Answers2

7

From Higher-Order Functions and Lambdas:

In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses:

So in your case, you have a function that takes three optional parameters. In the first implementation:

myObservable.subscribeBy { str -> }

You're using this feature to omit parentheses for the last lambda paramter (which is onNext). However, when you use the second implementation:

myObservable.subscribeBy({ throwable -> })

Since it's within the parentheses, it must be the first parameter, unless you were to explicitly name it as the last parameter, e.g.:

myObservable.subscribeBy(onNext = { str -> })
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • I've used `subscribeBy` before, but I didn't get what is the benefit(s) of this extension function in comparison with the `subscribe` itself?! – Dr.jacky Jul 15 '19 at 08:25
1

The subscribeBy method has the advantage of named parameters, which would resolve all the issues.

You can observe, that using the lambda notation sets the last unnamed parameter, while setting the parameter directly sets the first unnamed parameter.

If you name one of the parameters, you'll not be able to use the lambda notation anymore.

tynn
  • 38,113
  • 8
  • 108
  • 143