RX Observable.TakeWhile checks condition BEFORE each element but I need to perform the check after

前端 未结 6 2149
谎友^
谎友^ 2020-12-30 11:50

Observable.TakeWhile allows you to run a sequence as long as a condition is true (using a delegate so we can perform computations on the actual sequence objects), but it\'s

6条回答
  •  孤独总比滥情好
    2020-12-30 11:57

    I think you're after TakeWhile, not TakeUntil:

    var list = (new List(){1,2,3,4,5,6,7,8,9,10});
    var takeWhile = list
            .ToObservable()
            .Select((_, i) => Tuple.Create(i, _))
            .TakeWhile(tup => tup.Item1 < list.Count)
            .Do(_ => Console.WriteLine("Outputting {0}", _.Item2));
    

    Ok, the thing you want doesn't exist out of the box, at least I'm not aware of something with that particular syntax. That said, you can cobble it together fairly easily (and it's not too nasty):

    var fakeCmds = Enumerable
        .Range(1, 100)
        .Select(i => new SomeCommand() {CurrentIndex = i, TotalCount = 10})
        .ToObservable();
    
    var beforeMatch = fakeCmds
        .TakeWhile(c => c.CurrentIndex != c.TotalCount);
    var theMatch = fakeCmds
        .SkipWhile(c => c.CurrentIndex != c.TotalCount)
        .TakeWhile(c => c.CurrentIndex == c.TotalCount);
    var upToAndIncluding = Observable.Concat(beforeMatch, theMatch);
    

提交回复
热议问题