Example #1
0
        private async ValueTask <List <object?> > CreateStreamResultAsync(
            StreamDirective streamDirective)
        {
            IAsyncEnumerable <object?> enumerable = Selection.CreateStream(ResolverContext.Result !);
            IAsyncEnumerator <object?> enumerator = enumerable.GetAsyncEnumerator();
            var next = true;

            try
            {
                var list         = new List <object?>();
                var initialCount = streamDirective.InitialCount;
                var count        = 0;

                if (initialCount > 0)
                {
                    while (next)
                    {
                        count++;
                        next = await enumerator.MoveNextAsync().ConfigureAwait(false);

                        list.Add(enumerator.Current);

                        if (count >= initialCount)
                        {
                            break;
                        }
                    }
                }

                if (next)
                {
                    // if the stream has more items than the initial requested items then we will
                    // defer the rest of the stream.
                    OperationContext.Scheduler.DeferredWork.Register(
                        new DeferredStream(
                            Selection,
                            streamDirective.Label,
                            ResolverContext.Path,
                            ResolverContext.Parent <object>(),
                            count - 1,
                            enumerator,
                            ResolverContext.ScopedContextData));
                }

                return(list);
            }
            finally
            {
                if (!next)
                {
                    // if there is no deferred work we will just dispose the enumerator.
                    // in the case we have deferred work, the deferred stream handler is
                    // responsible of handling the dispose.
                    await enumerator.DisposeAsync().ConfigureAwait(false);
                }
            }
        }