我一直在试图找到一种不错的方法,但是我没有运气。
这是问题的简化版本:
import 'package:rxdart/rxdart.dart';
/// Input a list of integers [0,1,2,3,4]
/// map each of those integers to the corresponding index in the map
/// if the map updates, the output should update too.
///
/// The output should be a list of Strings:
/// ["Hi from 1", "Hi from 2"; "Hi from 3", "Hi from 4", "Hi from 5"]
BehaviorSubject<Map<int, String>> subject = BehaviorSubject(
seedValue: {
1: "Hi from 1",
2: "Hi from 2",
3: "Hi from 3",
4: "Hi from 4",
5: "Hi from 5",
}
);
void main() {
Observable.fromIterable([1, 2, 3, 4, 5])
.flatMap((index) => subject.stream.map((map) => map[index]))
.toList().asObservable()
.listen((data) {
print("List of data incoming $data");
});
}
运行此命令时,不会打印任何内容。这是因为主题从未完成,因此toList()
从未完成列表的构建。
用Observable.just(index + 2)
代替主题确实可以,因为Observable完成并且toList()
可以收集它们。
但是预期的行为是,每次更改主题时,示例都应发出新的字符串列表。
我们将不胜感激
谢谢!
答案 0 :(得分:1)
您可能想改用combineLatest
BehaviorSubject<Map<int, String>> subject = BehaviorSubject(seedValue: {
1: "Hi from 1",
2: "Hi from 2",
3: "Hi from 3",
4: "Hi from 4",
5: "Hi from 5",
});
void main() {
Observable.combineLatest2(
Observable.just([1, 2, 3, 4, 5]), subject.stream, combiner)
..listen(
(data) {
print("List of data incoming $data");
},
);
}
Iterable<String> combiner(List<int> indexes, Map<int, String> map) {
return indexes.map((index) => map[index]);
}
答案 1 :(得分:0)
编辑:发布此消息后不久,我意识到这完全取决于数据的公开方式:
如果您有一个签名类似Observable<String> getStringForInt(int number)
的方法,并且必须为列表中的每个项目调用它,那么我的解决方案就是为您解决的方法。 注意,如果以上方法始终订阅同一流,则更改该流将导致多次发射(因为CombineLatest会更新每个项目)。
但是,如果您有权访问整个数据容器(例如地图
原始答案
好吧,事实证明,使用rxDart的实现是不可能的。
combineLatest
构造函数最多仅支持9个流。
但是从那时起,实现了带有n-streams的CombineLatest,并且该问题的解决方案如下所示:
Map<int, BehaviorSubject<String>> subject2 = {
1: BehaviorSubject<String>(seedValue: "Subject 1"),
2: BehaviorSubject<String>(seedValue: "Subject 2"),
3: BehaviorSubject<String>(seedValue: "Subject 3"),
4: BehaviorSubject<String>(seedValue: "Subject 4"),
5: BehaviorSubject<String>(seedValue: "Subject 5"),
};
void main() async {
Observable.fromIterable([1, 2, 3, 4, 5])
.toList().asObservable()
.flatMap((numbers) =>
Observable.combineLatest<String, List<String>>(numbers.map((index) => subject2[index]), (strings) => strings))
.listen((data) {
print("List of data incoming $data");
});
await Future.delayed(Duration(seconds: 2));
subject2[1].add("I'm 42 now");
}
这将打印:
List of data incoming [Subject 1, Subject 2, Subject 3, Subject 4, Subject 5]
List of data incoming [I'm 42 now, Subject 2, Subject 3, Subject 4, Subject 5]