gpt4 book ai didi

c# - 我如何根据每个元素的条件循环可观察序列?

转载 作者:行者123 更新时间:2023-11-30 16:02:56 25 4
gpt4 key购买 nike

我有一个序列,我需要根据每个元素的条件重复它。例如,如果某个元素标有“失败”标志,我需要对其进行重新处理。我的问题是我找不到如何执行 while-loop 操作。

TakeWhile 几乎是我所需要的,但它不会 self 重复。

/*
* The following lines are just an example to comprehend the idea
*/
var observableSequence = sequence.ToObservable();
observableSequence
//This ´DoWhile´ did not worked because does not accept each element as argument
//and sequence at this point is not the same as `observableSequence`
.DoWhile(() => sequence.Any(item => !item.Failed))
.Where(item => item.Failed == true) //OK here i could put another condition for limited retries...
.Subscribe(item => {
try{
//Do stuff...
//. . .
item.Failed = false;
} catch
{
item.Failed = true;
}
});

最佳答案

我建议将原始序列与一个新的 Observable 合并,当对象失败时将其输入。

var retries = new ReplaySubject<Foo>();
var loopSequence = sequence.ToObservable().Merge(retries);

loopSequence
.Where(item => item.Failed)
.Subscribe(item =>
{
try{
//Do stuff
item.Failed = false;
} catch
{
item.Failed = true;
}
retries.OnNext(item);
});

通常认为更改可观察对象中对象的状态是不好的做法,因此您可能需要考虑创建转换:

loopSequence
.Where(item => item.Failed)
.Subscribe(item =>
{
try{
//Do stuff
retries.OnNext(new Item { ..., Failed = false });
} catch
{
retries.OnNext(new Item { ..., Failed = true });
}
});

您还应该非常小心这种模式,因为持续失败的项目会使您的程序执行进入一种无限循环。

关于c# - 我如何根据每个元素的条件循环可观察序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081111/

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