Reputation: 659
I am trying to migrate rxjava to rxjava2.
Map<String, Task> mCachedTasks;
I can convert it to Observable<List<Task>>
by using the following line of code. Observable.from(mCachedTasks.values()).toList()
However, I cannot convert it on rxjava2.
1- I tried the following code.
Observable.fromIterable(mCachedTasks.values())
but it returns Observable<Task>
2- I also tried to use fromArray
method, such as Observable.fromArray(mCachedTasks.values().toArray())
. That gives me Observable<Object>
.
How can I convert Map<String, Task>
to Observable<List<Task>>
on rxjava2?
Upvotes: 0
Views: 1650
Reputation: 321
public Observable> getOrganizations() {
List<Organization> list=new ArrayList<>(mcached.values());
if(mcached!=null && !mCacheIsDirty){
//return your map as list
return Observable.just(list);
}else {
mcached=new LinkedHashMap<>();
}
}
Upvotes: 0
Reputation: 2129
Another option is to create a lazy Observable:
Observable<List<Task>> taskListObservable = Observable.fromCallable(
//this will be called each time someone subscribes
() -> {
//do not forget the defensive copy
return new ArrayList<>(mCachedTasks.values());
}
);
This way mCachedTasks.values() will always get the fresh version and there will be no unnecessary flattening with toList() operator.
Upvotes: 0
Reputation: 498
Observable.fromIterable(mCachedTasks.values()).toList().toObservable();
Upvotes: 0
Reputation: 10267
I can convert it to Observable> by using the following line of code.
Observable.from(mCachedTasks.values()).toList()
That's an option, but you are unnecessarily flatting the list - the from()
, you taking a list and emit each item in onNext()
, and then collect it back as a list using toList()
, which waits for all the emissions and then emit single onNext()
with the collected list.
However, I cannot convert it on rxjava2. 1- I tried the following code.
Observable.fromIterable(mCachedTasks.values())
but it returnsObservable<Task>
fromIterable()
it's RxJava2 equivalent to from()
of RxJava1, you can use again toList()
- but in RxJava2 you will get Single
instead of Observable
(which is more concise API).
2- I also tried to use fromArray method, such as
Observable.fromArray(mCachedTasks.values().toArray())
. That gives meObservable<Object>
That's because toArray()
return array of Object
not Task
.
The solution is rather simple, you actually don't need RxJava for the transformation , you've got already an in-memory Map
, so first convert it to a List
(if you insisting on List
specifically):
List<Task> tasksList = new ArrayList<>(mCachedTasks.values());
and then use just()
operator to create an Observable
that emit this list as it's single value:
Observable<List<Task>> taskListObservable = Observable.just(tasksList);
Upvotes: 2