使用RxJava转换HashMap值

时间:2016-05-01 19:32:42

标签: android rx-java observable rx-android subscriber

是否有某种方式,通过'方式',我的意思是使用rx运算符,转换每个HashMap值(将hashmap键设置为值字段)并进入新的Hashmap或ArrList?

Observable<HashMap<String,Allergy>> observable = MyREST.getsAllergiesApi().getAllAllergiesRx();
    observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .unsubscribeOn(Schedulers.io())
            .subscribe(new Subscriber<HashMap<String, Allergy>>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG,"onCompleted");
                }

                @Override
                public void onError(Throwable e) {
                    Log.i(TAG,"onError");
                }

                @Override
                public void onNext(HashMap<String, Allergy> allergies) {

                    mView.displayAllergies(allergies);
                    Log.i(TAG,"onNeXt");
                }
            });

1 个答案:

答案 0 :(得分:5)

您可以在map中使用任何经典转换,也可以展平,映射和收集值。

Observable<Map<String, Allergy>> source = ...

source.map(map -> {
    HashMap<Allergy, Allergy> newMap = new HashMap<>();
    for (Allergy a : map.values()) {
        newMap.put(a, a);
    }
    return newMap;
})
.subscribe(...)

source.flatMapIterable(map -> map.values())
.toMap(v -> v)
.subscribe(...)