Reputation: 1
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"))
}
}
Upvotes: 0
Views: 965
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 itemsmap
-> transform your item to another itemtoList
-> transform a completed Observable to a Observable which emit a list of items from the completed ObservableUpvotes: 0
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
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
Reputation: 7368
Observable.from(getNames())
.map{ name -> new Person(name)}
.toList()
.subscribe(
list -> cachedPersons.addAll(list)
);
Upvotes: 4