我不知道它是否可以被认为是首选,
但在Reactive Extensions的“hot observables”上下文中,使用了成语“ Replay ”:
简短演示(C#):
using System;
using System.Reactive.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var observable = Observable.Interval(TimeSpan.FromSeconds(1))
.Do(l => Console.WriteLine("Publishing {0}", l)) //side effect to show it is running
.Replay(1); // buffer the last entry
Console.ReadKey();
using (observable.Connect()) // turn it "hot"
{
Console.ReadKey();
observable.Subscribe(i => Console.WriteLine("OnNext #1: {0}", i));
Console.ReadKey();
using (observable.Subscribe(i => Console.WriteLine("OnNext #2: {0}", i)))
{
Console.ReadKey();
} // unsubscribes #2 again
Console.ReadKey();
} // turn it "cold"
Console.ReadKey();
}
}
}
输出:
Publishing 0
Publishing 1
Publishing 2
OnNext #1: 2
Publishing 3
OnNext #1: 3
Publishing 4
OnNext #1: 4
Publishing 5
OnNext #1: 5
OnNext #2: 5
Publishing 6
OnNext #1: 6
OnNext #2: 6
Publishing 7
OnNext #1: 7
OnNext #2: 7
Publishing 8
OnNext #1: 8
OnNext #2: 8
Publishing 9
OnNext #1: 9
Publishing 10
OnNext #1: 10