问题
According the the MSDN documentation, the following code should output '5' to the console window. Instead, nothing is displayed.
static void Main(string[] args)
{
var o = new ReplaySubject<int>();
o.OnNext(0);
o.OnNext(1);
o.OnNext(2);
o.OnNext(3);
o.OnNext(4);
o.OnNext(5);
o.TakeLast(1).Subscribe(Console.WriteLine);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
Expected output:
5
Press any key to exit
Actual output:
Press any key to exit
Can anyone please explain why this is the case?
回答1:
That's because you never notify the completion of the sequence, so TakeLast
doesn't know the sequence is complete and continues to wait for the end of the sequence. This works as expected:
var o = new ReplaySubject<int>();
o.OnNext(0);
o.OnNext(1);
o.OnNext(2);
o.OnNext(3);
o.OnNext(4);
o.OnNext(5);
o.OnCompleted();
o.TakeLast(1).Subscribe(Console.WriteLine);
来源:https://stackoverflow.com/questions/6760212/why-does-takelastt-method-not-work-on-a-replaysubjectt