Reputation:
I keep getting expression can be replaced with a lambda for Java 8. How do I go about that? Here's one of the expressions I get that message on:
Observable.create(new ObservableOnSubscribe<Pair>() {
@Override
public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Pair> observableEmitter) throws Exception { ...
any idea?
Upvotes: 0
Views: 539
Reputation: 56433
Due to the fact that any interface which has a SAM
is by nature a functional interface, we can, therefore, do something like this:
Observable.create(e -> { /* do logic */ });
Note, that the above approach does not bubble up exceptions if any occur within the scope of create
. To accomplish such behavior with lambdas (anonymous functions) you can create a wrapper method and perform the logic there i.e:
public void subscribeWrapper(ObservableEmitter<Pair> e) throws java.lang.Exception {
// do logic
}
then you'd do:
Observable.create(e -> subscribeWrapper(e));
On the other hand, you could ignore creating the said method and use a try/catch
within the lambda statement block and rethrow the exception from there.
Upvotes: 2
Reputation:
This is how a lambda for this is created:
observableEmitter -> {
// your code here
}
You don't need the anonymous function or anything like that.
Putting it in the given code:
Observable.create(observableEmitter -> {
// your code here
});
You just replace the new ObservableOnSubs...
bit with the lambda.
Upvotes: 1