英文:
Rxjava lambda expressions
问题
我目前正在学习关于lambda表达式,并且对RxJava有一个问题。我认为lambda表达式可以用来避免创建匿名类,只有在接口具有单个抽象方法时才能使用。根据http://reactivex.io/上关于观察者的文档,它是一个接口。那么在一个接口内如何实现两个lambda表达式,就像这样:
Observable.<User>create(subscriber -> {
User updatedUser = userService.updateuser(usermapper.userdtotoentity(user));
subscriber.onNext(updatedUser);
}).subscribe(
user -> {
if (user != null) {
response.resume(user);
} else {
response.resume(Response.status(Status.NOT_FOUND).build());
}
},
error -> {
logger.debug("User with email_id:" + email_id + " is not present");
response.resume(error);
}
);
英文:
I'm currently learning about lambda expressions and have a question regarding RxJava. I thought that lambda expressions can be used so you don't have to create anonymous class and they can only be used if the interface has a single abstract method. Now according to http://reactivex.io/ documentation on observer, it's an interface. Then how is it possible to achieve two lambda expressions within a single interface such as this?
Observable.<User>create(subscriber -> {
User updatedUser = userService.updateuser(usermapper.userdtotoentity(user));
subscriber.onNext(updatedUser);
}).subscribe(
user -> {
if (user != null) {
response.resume(user);
} else {
response.resume(Response.status(Status.NOT_FOUND).build());
}
},
error -> {
logger.debug("User with email_id:" + email_id + " is not present");
response.resume(error);
}
);
答案1
得分: 1
Observable.subscribe
方法接受两个参数,均为函数接口类型。因此,您可以将 lambda 表达式作为两个参数的值进行传递。
如果您认为这样可以使代码更清晰,您可以将传递给参数的部分提取到局部变量中:
Action1 onNext = user -> { .... };
Action1 onError = error -> { .... };
Observable.<User>create(subscriber -> {....}).subscribe(onNext, onError);
英文:
The Observable.subscribe
method you are using accepts two parameters, both of which are of a functional interface type. Therefore you can pass a lambda expression as a value for both.
If you feel it will make the code clearer, you can extract the parameters you're passing to local variables:
Action1 onNext = user -> { .... };
Action1 onError = error -> { .... };
Observable.<User>create(subscriber -> {....}).subscribe(onNext, onError);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论