我在写一个用户界面。在某些操作中,我想知道来自特定IObservable的最新值。我怎么知道呢?
这是一个模拟我想要达到的效果的测试。你能帮忙修吗?
var selectedItemOut = new Subject<int?>();
// idea: define some other IObservable or subject here
var getLatest = new Func<int?>(() =>
{
// fix me
return 0;
});
Assert.AreEqual(null, getLatest());
selectedItemOut.OnNext(4);
Assert.AreEqual(4, getLatest());
selectedItemOut.OnNext(5);
Assert.AreEqual(5, getLatest());
selectedItemOut.OnNext(6);
selectedItemOut.OnNext(7);
Assert.AreEqual(7, getLatest());
如果你可以改变你的选择的主题是行为主题像Slugart有,那将是最好的(我会改变First()采取(1),但这只是我)。如果不能,则需要在函数作用域之外创建一个变量。
var selectedItemOut = new Subject<int?>();
// Hold the last result from the OnNext
int? results = null;
// idea: define some other IObservable or subject here
// update var each time OnNext is called
var lastResult = selectedItemOut.Subscribe(i => results = i);
// just a wrapper around the results var.
var getLatest = new Func<int?>(() => results);
Assert.AreEqual(null, getLatest());
selectedItemOut.OnNext(4);
Assert.AreEqual(4, getLatest());
selectedItemOut.OnNext(5);
Assert.AreEqual(5, getLatest());
selectedItemOut.OnNext(6);
selectedItemOut.OnNext(7);
Assert.AreEqual(7, getLatest());
//Need to tell the observable to stop updating the results var.
lastResultDispose.Dispose();
现在你的函数只是引用结果变量,你需要告诉它何时停止跟踪它。这不是很Rx,因为Rx是关于推入值的,你想从中获取一个值。
如果selectedItemOut可以是BehaviourSubject<int?>
,你可以使用它的Value
属性:
var selectedItemOut = new BehaviorSubject<int?>(null);
var getLatest = new Func<int?>(() =>
{
return selectedItemOut.Value;
});
否则CharlesNRice的答案看起来很好,或者你可以使用MostRecent
:
var mostRecent = selectedItemOut.MostRecent(null).GetEnumerator();
var getLatest = new Func<int?>(() =>
{
mostRecent.MoveNext();
return mostRecent.Current;
});
// need to clean up this up
mostRecent.Dispose()
如果您想要一个初始值(即使它是null),那么最近您可以使用BehaviorSubject
与First()
。关于上下文的更多信息将有助于找到更好的解决方案,因为不建议使用First()
。
var selectedItemOut = new BehaviorSubject<int?>(null);
// idea: define some other IObservable or subject here
Assert.AreEqual(null, selectedItemOut.First());
selectedItemOut.OnNext(4);
Assert.AreEqual(4, selectedItemOut.First());
selectedItemOut.OnNext(5);
Assert.AreEqual(5, selectedItemOut.First());
selectedItemOut.OnNext(6);
selectedItemOut.OnNext(7);
Assert.AreEqual(7, selectedItemOut.First());