如何用一行代码编写此代码?
public class RadGridColumnObservable
{
public RadGridColumnObservable(RadGridView grid, IMessageBus messageBus)
{
this.grid = grid;
this.messageBus = messageBus;
}
public IDisposable Initialize()
{
CreateStates();
return Observable
.Interval(TimeSpan.FromSeconds(1))
.Subscribe(_ => CheckUp());
}
//
private readonly RadGridView grid;
private readonly IMessageBus messageBus;
private readonly List<bool> states = new List<bool>();
//
private void CreateStates()
{
states.Clear();
states.AddRange(grid.Columns.Select(it => it.IsVisible));
}
private void CheckUp()
{
if (states.SequenceEqual(grid.Columns.Select(it => it.IsVisible))) return;
CreateStates();
messageBus.Publish(new NotifyMessage(MessageTypes.HistoryColumnsChanged));
}
}
想法是:我想检查“IsVisible”属性是否已更改。
我不喜欢使用这一行:private readonly List states=new List();
您可以通过以下方式获取您的IsVible
值:
private IObservable<List<bool>> CreateStatesObservable()
{
return Observable.Interval(TimeSpan.FromSeconds(1))
.Select(_ => grid.Columns.Select(it => it.IsVisible));
}
然后使用扫描来跟踪您以前的值:
public void Initialize()
{
var observable =
CreateStatesObservable()
.Scan(
(prev: default(List<bool>), actual: default(List<bool>)),
(acc, c) => (acc.current, current))
.Where(values => !values.actual.SequenceEqual(values.prev))
.Select(_ => true);
}
或者您可以使用“延迟”并执行以下操作:
public void Initialize2()
{
var observable = CreateStatesObservable();
var deferred =
Observable.Defer(
() =>
{
List<bool> previous = null;
return observable.Select(
values =>
{
if (previous is null)
{
previous = values;
return false;
}
if (!values.SequenceEqual(previous))
{
previous = values;
return true;
}
return false;
});
})
.Where(value => value);
}
这两个选项都应该为您提供一个observable,它仅在其中一列可见时产生一个值。(该值仅为
真值
)