這聽起來像你想這樣的數據流:
seed profiles --> source --> get related --> output
^ |
| v
-<--- transform <-----
這看起來是解決地方的一般問題是不是特定的一個容易或更容易的情況下,所以我會提出一個通用的「反饋「應該給你的積木功能,你需要:
編輯:固定函數來完成
IObservable<TResult> Feedback<T, TResult>(this IObservable<T> seed,
Func<T, IObservable<TResult>> produce,
Func<TResult, IObservable<T>> feed)
{
return Observable.Create<TResult>(
obs =>
{
var ret = new CompositeDisposable();
Action<IDisposable> partComplete =
d =>
{
ret.Remove(d);
if (ret.Count == 0) obs.OnCompleted();
};
Action<IObservable<T>, Action<T>> ssub =
(o, n) =>
{
var disp = new SingleAssignmentDisposable();
ret.Add(disp);
disp.Disposable = o.Subscribe(n, obs.OnError,() => partComplete(disp));
};
Action<IObservable<TResult>, Action<TResult>> rsub =
(o, n) =>
{
var disp = new SingleAssignmentDisposable();
ret.Add(disp);
disp.Disposable = o.Subscribe(n, obs.OnError,() => partComplete(disp));
};
Action<T> recurse = null;
recurse = s =>
{
rsub(produce(s),
r =>
{
obs.OnNext(r);
ssub(feed(r), recurse);
});
};
ssub(seed, recurse);
return ret;
});
}
在你的情況下,T
和TResult
看起來是一樣的,所以feed
將是身份函數。 produce
將用於實施步驟2和3
我測試了這個功能的一些示例代碼的功能:
void Main()
{
var seed = new int[] { 1, 2, 3, 4, 5, 6 };
var found = new HashSet<int>();
var mults = seed.ToObservable()
.Feedback(i =>
{
return Observable.Range(0, 5)
.Select(r => r * i)
.TakeWhile(v => v < 100)
.Where(v => found.Add(v));
},
i => Observable.Return(i));
using (var disp = mults.Dump())
{
Console.WriteLine("Press any key to stop");
Console.ReadKey();
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
static IDisposable Dump<T>(this IObservable<T> source)
{
return source.Subscribe(item => Console.WriteLine(item),
ex => Console.WriteLine("Error occurred in dump observable: " + ex.ToString()),
() => Console.WriteLine("Dump completed"));
}
如果我是用硬件的術語,你在尋找一個多路複用器,解複用器? – JerKimball 2013-03-08 19:41:25
@JerKimball我不確定你在這方面的含義。 – 2013-03-08 22:07:06
嗯......讓我嘗試重寫:你有多個源,你想把它們打成一個單一的流,然後從這個單一流中「解除」出現回到相應的多個流? – JerKimball 2013-03-08 22:28:26