I have got Future<List<Directory>> dave
. dave
is a Future, but in the future it might change into a Stream. Therefore I think ahead and subscribe to him like this:
var daveSub = Stream<List<Directory>>
.fromFuture(dave())
.listen((List<Directory> folders) {
...
});
If dave
gives me a directory with path under some /root/folder
, I want to doStuff();
and cancel my subscription to dave
. My current approach looks like this:
var daveSub = Stream<List<Directory>>
.fromFuture(dave())
.listen((List<Directory> folders) {
for (final Directory folder in folders) {
if (folder.path.startsWith('/root/folder')) {
doStuff(folder);
daveSub.cancel();
}
}
});
But this doesn't look right to me, especially the for cycle inside listener. Using a basic features of Future it doesn't look right as well:
dave()
.then((List<Directory> folders) {
for (final Directory folder in folders) {
if (folder.path.startsWith('/root/folder')) {
doStuff(folder);
}
}
});
Is there some better way to handle dave
's list items (and maybe avoid the nested for cycle)?
I would expect something like this:
Stream<Directory>
.fromFuture(dave())
.firstItemWhere((Directory folder) => folder.path.startsWith('/root/folder'))
.then((Directory folder) {
doStuff(folder);
});
or this:
dave()
.firstItemWhere(((Directory folder) => folder.path.startsWith('/root/folder')) {
doStuff(folder);
});
or at least:
dave()
.then((List<Directory> folders) {
for (final Directory folder in folders if folder.path.startsWith('/root/folder')) {
doStuff(folder);
}
});
>` to a `Stream`, perhaps by `var stream = future.asStream().expand((x)=>x);`. Then you get one element at a type instead of just one list of the elements.
Then the `firstWhere` should work.
– lrn Mar 01 '21 at 08:52