Rx how to create a sequence from a pub/sub pattern

混江龙づ霸主 提交于 2019-12-09 23:18:20

问题


I'm trying to evaluate using Rx to create a sequence from a pub/sub pattern (i.e. classic observer pattern where next element is published by the producer(s)). This is basically the same as .net events, except we need to generalize it such that having an event is not a requirement, so I'm not able to take advantage of Observable.FromEvent. I've played around with Observable.Create and Observable.Generate and find myself end up having to write code to take care of the pub/sub (i.e. I have to write producer/consumer code to stash the published item, then consume it by calling IObserver.OnNext() with it), so it seems like I'm not really taking advantage of Rx...

Am I looking down the correct path or is this a good fit for Rx?

Thanks


回答1:


Your publisher just exposes some IObservables as properties. And your consumers just Subscribe to them (or do any Rx-fu they want before subscribing).

Sometimes this is as simple as using Subjects in your publisher. And sometimes it is more complex because your publisher is actually observing some other observable process.

Here is a dumb example:

public class Publisher
{
    private readonly Subject<Foo> _topic1;

    /// <summary>Observe Foo values on this topic</summary>
    public IObservable<Foo> FooTopic
    {
       get { return _topic1.AsObservable(); }
    }

    private readonly IObservable<long> _topic2;

    /// <summary>Observe the current time whenever our clock ticks</summary>
    public IObservable<DateTime> ClockTickTopic
    {
        get { return _topic2.Select(t => DateTime.Now); }
    }

    public Publisher()
    {
         _topic1 = new Subject<Foo>();
         // tick once each second
         _topic2 = Observable.Interval(TimeSpan.FromSeconds(1));
    }

    /// <summary>Let everyone know about the new Foo</summary>
    public NewFoo(Foo foo) { _topic1.OnNext(foo); }
}


// interested code...
Publisher p = ...;
p.FooTopic.Subscribe(foo => ...);

p.ClickTickTopic.Subscribe(currentTime => ...);

// count how many foos occur during each clock tick
p.FooTopic.Buffer(p.ClockTickTopic)
    .Subscribe(foos => Console.WriteLine("{0} foos during this interval", foos.Count));



回答2:


Using RX is definitely a good fit for pub/sub. Here is a demo that illustrates the simplest possible pub/sub pattern using IObservable and RX.

Add Reactive Extensions (RX) to your project using NuGet, search for rx-main and install Reactive Extensions - Main Library.

using System;
using System.Reactive.Subjects;

namespace RX_2
{
    public static class Program
    {
        static void Main(string[] args)
        {
            Subject<int> stream = new Subject<int>();

            stream.Subscribe(
                o =>
                {
                    Console.Write(o);
                });

            stream.Subscribe(
                o =>
                {
                    Console.Write(o);
                });

            for (int i = 0; i < 5; i++)
            {
                stream.OnNext(i);
            }

            Console.ReadKey();
        }
    }
}

When executed, the code outputs this:

0011223344


来源:https://stackoverflow.com/questions/17974287/rx-how-to-create-a-sequence-from-a-pub-sub-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!