0

我对 RXJava 很陌生。我正在定义多个需要在初始化中做几乎相同的事情的主题,但它们的泛型类型不同。目前我的解决方案如下所示:

BehaviorSubject<PepPoint> mUpdateSubject = BehaviorSubject.create();

BehaviorSubject<String> mMessageSubject = BehaviorSubject.create();
mMessageSubject.onNext(mMessage);//type string
mMessageSubject.distinctUntilChanged().skip(1).debounce(5, TimeUnit.SECONDS).sample(1, TimeUnit.MINUTES).subscribe(this::onChanged);

BehaviorSubject<Double> mTriggerRadiusSubject = BehaviorSubject.create();
mTriggerRadiusSubject.onNext(mTriggerRadius);//type double
mMessageSubject.distinctUntilChanged().skip(1).debounce(5, TimeUnit.SECONDS).sample(1, TimeUnit.MINUTES).subscribe(this::onChanged);

BehaviorSubject<SimpleLocation> observableLocation = BehaviorSubject.create();
observableLocation.onNext(mLocation);//type Location
observableLocation.distinctUntilChanged().skip(1).debounce(5, TimeUnit.SECONDS).sample(1, TimeUnit.MINUTES).subscribe(this::onChanged);

    /*And same for many several other variables*/

你可以看到有很多重复。所以我希望达到的效果最好是这样的:

{
BehaviorSubject<PepPoint> mUpdateSubject = BehaviorSubject.create();
Map<Object, BehaviorSubject> subjectMap = new TreeMap<>();
subjectMap.put(mMessage, BehaviorSubject.<String>create());
subjectMap.put(mTriggerRadius, BehaviorSubject.<Double>create());
subjectMap.put(mLocation, BehaviorSubject.<Location>create());
subjectMap.put(mPreconditions, BehaviorSubject.<List<String>>create());
subjectMap.put(mLanguage, BehaviorSubject.<String>create());

for(Map.Entry<Object, BehaviorSubject> entry:subjectMap.entrySet()){
     entry.getValue().onNext(entry.getKey());
        mMessageSubject
                .distinctUntilChanged()
                .skip(1)
                .debounce(5,TimeUnit.SECONDS)
                .subscribe(this::onChange);
    }
}

我不明白为什么这不起作用。我也试过 Map<? super Object, BehaviorSubject<? super Object>> subjectMap = new TreeMap<>(); 建议?谢谢

4

1 回答 1

0

因为我真的不需要将主题放在集合中,所以我通过创建一个处理所有与 for 循环相同的事情的方法来解决这个问题。

解决方案:

public void initSubjects() {
    mUpdateSubject = BehaviorSubject.create();

    initSingleSubject(mMessage, mMessageSubject = BehaviorSubject.<String>create());
    initSingleSubject(mTriggerRadius, mTriggerRadiusSubject = BehaviorSubject.<Double>create());
    initSingleSubject(mLanguage, mLanguageSubject = BehaviorSubject.<String>create());
    initSingleSubject(mPreconditions, mPreconditionsSubject = BehaviorSubject.<List<String>>create());
    initSingleSubject(mLocation, mLocationSubject = BehaviorSubject.<SimpleLocation>create());
}

private void initSingleSubject(Object value, BehaviorSubject subject){
    subject.onNext(value);
    mUpdateSubject
            .distinctUntilChanged()
            .skip(1)
            .debounce(5,TimeUnit.SECONDS)
            .subscribe(this::onUpdate);
}
于 2016-03-27T13:56:00.540 回答