How to create a range of Observable<int> and complete when condition is true

Viewed 288

The below code will run for all sequences, I want the Observable to stop raising events after the condition is true.

private IObservable<string> EnsureIndexWithCounter(string index)
        {
            return Observable.Range(0, 5)
                             .SelectMany(p => IncrementCounterIfIndexExistsAsync(index, p)
                                                    .ToObservable()
                                                    .RepeatUntil(x => !x.Item1, 5))
                             .TakeWhile(p => !p.Item1)
                             .Select(p => p.Item2);
        }

        // Will be invoked 4 times, should be invoked as long the Item1 of the return tuple is true
        private async Task<Tuple<bool, string>> IncrementCounterIfIndexExistsAsync(string index, int counter)
        {
            var existsResponse = await Client.IndexExistsAsync(new IndexExistsRequest(index)).ConfigureAwait(false);
            var newCounter = existsResponse.Exists ? ++counter : counter;
            return Tuple.Create(existsResponse.Exists, $"{index}_{newCounter}");
        }
0 Answers
Related