我正在使用UniRX插件在C#的Unity中工作。对于那些不熟悉它的人来说,UniRX是C# Reactive扩展的一个实现,它被移植回C# .Net 2(这是unity从5.3.5版开始使用的)。我试图做的是从类型A中的一个IObservable中获取数据,使用System.Func将其转换,并自动将结果发布到类型B的新IObservable中。我写了几行代码来完成此操作,但我觉得这应该是自动包含在Reactive扩展中的东西(但我只是在文档中找不到要调用的正确方法)。我写的代码如下:
private class ObserverableBridge<TIn, TOut> {
public ReactiveProperty<TOut> outStream;
public ObserverableBridge(IObservable<TIn> input, System.Func<TIn, TOut> converter) {
this.outStream = new ReactiveProperty<TOut>();
input.Subscribe((inValue) => this.outStream.Value = converter(inValue));
}
}
public static IObservable<TOut> Bridge<TIn, TOut>(this IObservable<TIn> a, System.Func<TIn, TOut> converter) {
return new ObserverableBridge<TIn, TOut>(a, converter).outStream;
}它的用法如下:
ReactiveProperty<float> input = new ReactiveProperty<float>(0.1f);
IObservable <int> output = input.Bridge((inFloat) => Mathf.RoundToInt(inFloat));
output.Subscribe((a) => { Debug.Log("a = " + a); });
for(int i = 1; i<3; i++) {
input.Value = i + 0.1f;
}并产生如下输出:
a = 0
a = 1
a = 2我好奇的是,有一种方法可以内置到Reactive扩展中(在我看来应该有),这样我就不需要使用我自己的Bridge系统了。
提前感谢您的帮助!
发布于 2016-08-11 11:09:21
试试Select()
ReactiveProperty<float> input = new ReactiveProperty<float>(0.1f);
input.Select<float, int>(Mathf.RoundToInt).Subscribe(a => Debug.LogFormat("a = {0}", a));https://stackoverflow.com/questions/37645694
复制相似问题