我在参加
主题时遇到了麻烦public Subject<IEnumerable<Person>> PersonDataSubject;
将其转换为:
public Subject<IEnumerable<BornInYear>> BornInYearSubject;
...使用一些linq聚合。
以下示例将其置于更多上下文中,我正在努力解决如何从订阅PersonDataSubject将IEnumerable导入BornInYearSubject。
无论我尝试什么,我最终得到的是IObservable<BornInYear>
,而不是IObservable<IEnumerable<BornInYear>>
。
目标是让班级的客户能够订阅这两个科目,并在每个&#39; next&#39;上获得相应类型的IEnumerable。通知。
public class ReactiveTest
{
public class Person
{
public string name;
public DateTime dob;
};
public class BornInYear
{
public int Year;
public int Count;
}
public Subject<IEnumerable<Person>> PersonDataSubject = new Subject<IEnumerable<Person>>();
public Subject<IEnumerable<BornInYear>> BornInYearSubject= new Subject<IEnumerable<BornInYear>>();
public void LoadData()
{
// Go to hypotheritical web service and get batch of people.
IEnumerable<Person> people = WebService.Fetch();
// Notify subscribers we have a fresh batch of data.
PersonDataSubject.OnNext(people);
}
public ReactiveTest()
{
// Hookup BornInYearSubject to listen to PersonDataSubject and publish the summarised data.
PersonDataSubject.Subscribe(pd => pd.GroupBy(p => p.dob.Year)
.Select(ps => new BornInYear { Year = ps.Key, Count = ps.Count()})
.AsParallel()
);
// How do I get the results of this out and published onto BornInYearSubject?
}
}
现在我知道我可以使用Task.Factory.StartNew(...)...
作为PersonDataSubject的订阅OnNext来实现这一点,但我相信它必须能够保持更多的Reactive?
答案 0 :(得分:1)
怎么样:
PersonDataSubject
.GroupBy(x => x.Dob.Year)
.Select(x => x.Aggregate(new List<BornInYear>(), (acc, x) => { acc.Add(new BornInYear { Year = ps.Key }); return acc; }))
答案 1 :(得分:0)
好的,这很有用。感谢你们的想法 - 事后看来答案显然非常明显!
using System;
using System.Collections.Generic;
using System.Linq;
namespace TestReactive
{
public class ReactiveTest
{
public class Person
{
public string name;
public DateTime dob;
};
public class BornInYear
{
public int Year;
public int Count;
}
public Subject<IEnumerable<Person>> PersonDataSubject = new Subject<IEnumerable<Person>>();
public Subject<IEnumerable<BornInYear>> BornInYearSubject = new Subject<IEnumerable<BornInYear>>();
public void LoadData()
{
IEnumerable<Person> people = new List<Person> {
new Person() {name = "Bill", dob = DateTime.Now.AddYears(-10)},
new Person() {name = "Pete", dob = DateTime.Now.AddYears(-5)},
new Person() {name = "Judy", dob = DateTime.Now.AddYears(-1)},
new Person() {name = "Mike", dob = DateTime.Now.AddYears(-5)},
new Person() {name = "Jake", dob = DateTime.Now.AddYears(-5)},
new Person() {name = "Fred", dob = DateTime.Now.AddYears(-13)},
};
// Notify subscribers we have a fresh batch of data.
PersonDataSubject.OnNext(people);
}
public ReactiveTest()
{
var subj = PersonDataSubject.Select(pds => pds.GroupBy(pd => pd.dob.Year)
.Select(p => new BornInYear {
Year = p.Key, Count = p.Count()
}).AsParallel());
subj.Subscribe(BornInYearSubject);
BornInYearSubject.Subscribe( x=> Console.WriteLine("{0}", x.Count()));
LoadData();
}
}
class Program
{
static void Main(string[] args)
{
ReactiveTest rt = new ReactiveTest();
}
}
}