如何将迭代更改为反应式 (Rx)
How can I change an iteration to be Reactive (Rx)
我想将以下代码更改为基于 Observable 的代码:
// 'assets' is a IReadOnly list of StorageFile (approx. 10-20 files)
foreach (var file in assets)
{
img.Source = new BitmapImage(new Uri(file.Path));
img.ImageOpened += async (sender, e) =>
{
// Do some work (can contain Task-based code)
};
}
但是当我尝试更改它时,我遇到了一些设计问题:
assets
.ToObservable()
.Select(file =>
{
img.Source = new BitmapImage(new Uri(file.Path));
return img.Events().ImageOpened;
})
.Switch()
.Select(event =>
{
// Now I'm stuck, I don't have the file...
})
.Subscribe(
_ =>
{
},
ex => System.Diagnostics.Debug.WriteLine("Error on subscribing to ImageOpened"))
.DisposeWith(_subscriptions);
我觉得我的做法是错误的...
由于我的图像控件的另一个限制,最后我需要改变我的逻辑,但我的解决方案是使用 Zip 的以下方向:
Observable
.Zip(
assets
.ToObservable()
.Do(file => imageControl.Source = new BitmapImage(new Uri(file.Path))),
imageControl
.Events() // Extension class for my events
.ImageOpened,
(asset, _) =>
{
// Do some work ...
})
.Subscribe(
_ => { },
ex => System.Diagnostics.Debug.WriteLine("Error on subscribing to Zip"));
.DisposeWith(_subscriptions);
我想将以下代码更改为基于 Observable 的代码:
// 'assets' is a IReadOnly list of StorageFile (approx. 10-20 files)
foreach (var file in assets)
{
img.Source = new BitmapImage(new Uri(file.Path));
img.ImageOpened += async (sender, e) =>
{
// Do some work (can contain Task-based code)
};
}
但是当我尝试更改它时,我遇到了一些设计问题:
assets
.ToObservable()
.Select(file =>
{
img.Source = new BitmapImage(new Uri(file.Path));
return img.Events().ImageOpened;
})
.Switch()
.Select(event =>
{
// Now I'm stuck, I don't have the file...
})
.Subscribe(
_ =>
{
},
ex => System.Diagnostics.Debug.WriteLine("Error on subscribing to ImageOpened"))
.DisposeWith(_subscriptions);
我觉得我的做法是错误的...
由于我的图像控件的另一个限制,最后我需要改变我的逻辑,但我的解决方案是使用 Zip 的以下方向:
Observable
.Zip(
assets
.ToObservable()
.Do(file => imageControl.Source = new BitmapImage(new Uri(file.Path))),
imageControl
.Events() // Extension class for my events
.ImageOpened,
(asset, _) =>
{
// Do some work ...
})
.Subscribe(
_ => { },
ex => System.Diagnostics.Debug.WriteLine("Error on subscribing to Zip"));
.DisposeWith(_subscriptions);