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

倾然丶 夕夏残阳落幕 提交于 2019-12-04 20:35:23

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

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