gpt4 book ai didi

dart - RxDart,将列表的每个项目映射到来自永无止境的流的另一个对象

转载 作者:行者123 更新时间:2023-12-03 02:57:01 25 4
gpt4 key购买 nike

我一直在试图找到一种很好的方法来做到这一点,但是我没有运气。

这是问题的简化版本:

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()能够收集它们。

但是预期的行为是,每次更改主题时,示例都应发出新的字符串列表。

任何帮助,将不胜感激,

谢谢!

最佳答案

您可能想改用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]);
}

关于dart - RxDart,将列表的每个项目映射到来自永无止境的流的另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53478354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com