0
  • I have a method: Observable<List<String>> getNames();

  • I have object Person with constructors Person() and Person(String name)

  • Also there is a empty list ArrayList<Person> cachedPersons.

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")) 
       }
    }

4 Answers 4

4
Observable.from(getNames())
    .map{ name -> new Person(name)}
    .toList()
    .subscribe(
        list -> cachedPersons.addAll(list)
    );
Sign up to request clarification or add additional context in comments.

2 Comments

Couldn't you just do Observable.from(getNames()).subscribe(name -> cachedPersons.add(name)); ?
Not sure if i understand correctly, but i still need to return Observable<List<String>> from my function(not List<Person>), and add to cachedPersons "by the way", like inside this stream
0

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.

Comments

0

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.

Comments

0
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

2 Comments

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
added short description.. @yivi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.