-1

我如何在不使用主题的情况下在 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。

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

4

1 回答 1

2

我实现类似的方法是MemberAdded在我的MemberRepository. 然后,您可以使用Observable.FromEventor Observable.FromEventPattern(区别在这里)订阅事件,如下所示:

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!));

In regard to your second question, you should avoid static properties - consider using something like the Event Aggregator pattern instead

于 2013-02-01T17:22:25.893 回答