【问题标题】:RxJava convert Single<String> object to String classRxJava 将 Single<String> 对象转换为 String 类
【发布时间】:2021-04-07 06:41:19
【问题描述】:

是否可以将 Single 对象转换为 String 类?

Single stringSingle = Single.just(User.getName());

字符串 s = "";

s=stringSingle;

如何将 stringSingle 分配给 s 变量?

【问题讨论】:

标签: java rx-java micronaut


【解决方案1】:

你可以有这样的东西。

import rx.Single;
import lombok.Getter;

public class TestClass {

  public static void main(String[] args) {
     Single<User> stringSingle = Single.just(new User("Peter", 9));
   final String[] s = new String[1];

   //Asynchronous and advisable 
   stringSingle.subscribe( result -> {
      s[0] = result.toString();
    });
    System.out.println(s[0]);
     
     //Blocking and not very advisible way of getting the value
    String s2 =   stringSingle.toBlocking().value().toString();
    System.out.println(s2);
  }
}

//Example of a possible User class to use.
class User{
  @Getter
  private String name;
  @Getter
  private int age ;

  public User( String nm,  int ag){
    name = nm;
    age = ag;
  }

  @Override
  public String toString(){
    return "name " + getName() + " and age " + getAge();
  }
}

结果是

name Peter and age 9
name Peter and age 9

【讨论】:

  • 谢谢,但我使用的是 Reactive Java,控制器中有 @ExecuteOn,我认为使用 toBlocking() 不是一个好主意。我想从作为 Single> 对象的响应中获取,来自响应(主体)的对象属性。你有什么想法吗?
  • 您可以订阅 Single observable 并异步获取结果(当值准备好时)。我提供的解决方案中已经有一个示例。 //Asynchronous and advisable stringSingle.subscribe( result -&gt; { s[0] = result.toString(); });还有一些其他的例子here
猜你喜欢
  • 2012-04-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2011-02-07
  • 2013-10-16
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多