订阅对象内容更改的RxAndroid

时间:2016-03-27 13:43:00

标签: java generics wildcard-mapping

我对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<>(); 建议? 感谢

1 个答案:

答案 0 :(得分:0)

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

解决方案:

<Grid Width="17cm" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TextBlock HorizontalAlignment="Right"  Text="Invoice Nr:"/>
    <TextBox Grid.Column="1" HorizontalAlignment="Left"  Width="2cm"  />

</Grid>