Observable.From用于未来事件而不是主题

时间:2013-02-01 15:55:33

标签: c# system.reactive

如何在不使用主题的情况下在RX中实现这种情况。我已经阅读了很多,而我似乎无法弄清楚

    public class Member 
{
    public int Id { get; private set; }
    public string Email { get; private set; }

    public Member(string email)
    {
        this.Email = email;
    }
}

public class MemberRepository
{
    public void AddMember(Member member)
    {
        // save member
        memberAdded.OnNext(member);
    }

    private Subject<Member> memberAdded = new Subject<Member>();
    public IObservable<Member> MemberAdded { get { return memberAdded.AsObservable(); } }
}

public class MemberController
{
    public void Create(Member item)
    {
        var repository = new MemberRepository();
        var subs = repository.MemberAdded.Subscribe(x => SendMail(x));
        repository.AddMember(item);
    }

    private void SendMail(Member value)
    {
        // send welcome mail
    }
}

我不知道如何初始化IObservable MemberAdded,因为如果它没有Subject支持者,它总是为null,我也不知道如何在以后的函数中调用OnNext。

最后,将observable作为静态属性和所有订阅代码放在一个地方是否有问题?

1 个答案:

答案 0 :(得分:2)

我实现类似的方法是在MemberAdded上公开正常的C#事件MemberRepository。然后,您可以使用Observable.FromEventObservable.FromEventPattern(差异为here)订阅此类事件:

public class MemberRepository
{
    public void AddMember(Member member)
    {
        // save member
        if (MemberAdded != null)
            MemberAdded(new MemberEventArgs(member, MemberEvent.Add));
    }

    public event EventHandler<MemberEventArgs> MemberAdded;
}

...

Observable.FromEventPattern<MemberEventArgs>(h => memberRepository.MemberAdded += h,
                                             h => memberRepository.MemberAdded -= h)
    .Select(e => e.Member)
    .Subscribe(m => Console.WriteLine("Member "+m+" added!));

关于你的第二个问题,你应该避免使用静态属性 - 考虑使用类似Event Aggregator模式的东西