ArsSiegfried
ArsSiegfried

Reputation: 1

Create list with objects from another list using RxJava

What I need: In my method using RxJava fill array with Person using constructor<String> from List<String> like this:

ArrayList<String> cachedPersons = new ArrayList<Person>();

Observable<List<String>> getNames(){
       Observable.from(getNames())
       .map{
           //cachedPersons.addAll(/*add new Person with corresponding String*/)
           //with List("John","Sara","David")
           //create cachedPersons = List(Person1("John"),Person2("Sara"),Person3("David")) 
       }
    }

Upvotes: 0

Views: 965

Answers (4)

Ankit Kumar
Ankit Kumar

Reputation: 3723

Observable<SourceObjet> source = ...// get first list from here
   source.flatMapIterable(list -> list)
  .map(item -> new ResultsObject().convertFromSource(item))
  .toList()
  .subscribe(transformedList -> ...);

If your Observable emits a List, you can use these operators:

  • flatMapIterable -> transform your list to an Observable of items
  • map -> transform your item to another item
  • toList -> transform a completed Observable to a Observable which emit a list of items from the completed Observable

Upvotes: 0

Vasili Fedotov
Vasili Fedotov

Reputation: 1171

Maybe this

Observable.from(getNames()) 
      .doOnNext(name -> cachedPersons.add(new Person(name)))
      .toList() 
      .subscribe();

This way you are just filling it without changing the stream value.

Upvotes: 0

Misha Akopov
Misha Akopov

Reputation: 13057

The problem is that you are trying to fill needed ArrayList from map() method, and it is wrong.

It will never be executed until you make a subscription. You are not doing it in your code, so your ArrayList will not be filled with above code.

Do subscription and in subscription onNext you can fill your ArrayList.

Upvotes: 0

Benjamin
Benjamin

Reputation: 7368

Observable.from(getNames())
    .map{ name -> new Person(name)}
    .toList()
    .subscribe(
        list -> cachedPersons.addAll(list)
    );

Upvotes: 4

Related Questions