简体   繁体   中英

RxJava convert Single<String> object to String class

Is there a posibility to convert a Single object to String class?

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

String s = "";

s = stringSingle;

How can I assign stringSingle to the s variable?

You could have something like this.

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();
  }
}

Results is

name Peter and age 9
name Peter and age 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM