Search code examples
javarx-javamicronaut

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?


Solution

  • 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