RxJava lambda表达式

huangapple go评论79阅读模式
英文:

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.&lt;User&gt;create(subscriber -&gt; {

    User updatedUser = userService.updateuser(usermapper.userdtotoentity(user));
    subscriber.onNext(updatedUser);

}).subscribe(

     user -&gt; {
       if (user != null) {
          response.resume(user);
      } else {
        response.resume(Response.status(Status.NOT_FOUND).build());
      }
    }, 

     error -&gt; {
        logger.debug(&quot;User with email_id:&quot; + email_id + &quot; is not present&quot;);
        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 -&gt; { .... };

Action1 onError = error -&gt; { .... };

Observable.&lt;User&gt;create(subscriber -&gt; {....}).subscribe(onNext, onError);

huangapple
  • 本文由 发表于 2020年8月23日 20:44:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63547102.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定