对于此类问题,提供测试场景非常有用。你已经给出了你想要的一个很棒的小大理石图,然后将它转换为测试用例真的很容易。然后其他论坛读者可以获取测试代码,实施他们的想法并知道他们是否满足您的要求。
[Test]
public void Should_only_get_latest_value_from_Y_but_not_while_x_produes()
{
// 11111111112222222222333
// 12345678901234567890123456789012
//xs --x---x---x---x-------x---x---x-
// \ \ \
//ys ----y-----------y---y---y-------
// | | |
//rs ----x-----------x-------x-------
// y y y
var testScheduler = new TestScheduler();
// 11111111112222222222333
// 12345678901234567890123456789012
//xs --x---x---x---x-------x---x---x-
var xs = testScheduler.CreateColdObservable(
new Recorded<Notification<char>>(3, Notification.CreateOnNext('1')),
new Recorded<Notification<char>>(7, Notification.CreateOnNext('2')),
new Recorded<Notification<char>>(10, Notification.CreateOnNext('3')),
new Recorded<Notification<char>>(15, Notification.CreateOnNext('4')),
new Recorded<Notification<char>>(23, Notification.CreateOnNext('5')),
new Recorded<Notification<char>>(27, Notification.CreateOnNext('6')),
new Recorded<Notification<char>>(31, Notification.CreateOnNext('7')));
// 11111111112222222222333
// 12345678901234567890123456789012
//ys ----y-----------y---y---y-------
var ys = testScheduler.CreateColdObservable(
new Recorded<Notification<char>>(5, Notification.CreateOnNext('A')),
new Recorded<Notification<char>>(17, Notification.CreateOnNext('B')),
new Recorded<Notification<char>>(21, Notification.CreateOnNext('C')),
new Recorded<Notification<char>>(25, Notification.CreateOnNext('D')));
//Expected :
//Tick x y
//5 1 A
//17 4 B
//25 5 D
var expected = new[]
{
new Recorded<Notification<Tuple<char, char>>>(5, Notification.CreateOnNext(Tuple.Create('1', 'A'))),
new Recorded<Notification<Tuple<char, char>>>(17, Notification.CreateOnNext(Tuple.Create('4', 'B'))),
new Recorded<Notification<Tuple<char, char>>>(25, Notification.CreateOnNext(Tuple.Create('5', 'D')))
};
var observer = testScheduler.CreateObserver<Tuple<char, char>>();
//Passes HOT, fails Cold. Doesn't meet the requirements due to Timeout anyway.
//xs.Select(x => ys.Take(1)
// .Timeout(TimeSpan.FromSeconds(0.5),
// Observable.Empty<char>())
// .Select(y => Tuple.Create(x, y))
// )
// .Switch()
// .Subscribe(observer);
//Passes HOT. Passes Cold
xs.Join(ys,
_ => xs.Merge(ys),
_ => Observable.Empty<Unit>(),
Tuple.Create)
.Subscribe(observer);
testScheduler.Start();
//You may want to Console.WriteLine out the two collections to validate for yourself.
CollectionAssert.AreEqual(expected, observer.Messages);
}
PS 顺便说一句,Merge 很好地使用了答案。