Esempio n. 1
0
        /// <summary>
        /// Cancel a subscription that was created by calling <see cref="Subscribe{T}(IQueryable{T}, SubscriptionOptions, Expression{Func{T, IQueryable}}[])"/>.
        /// <para />
        /// Removing a subscription will delete all objects from the local Realm that were matched
        /// only by that subscription and not any remaining subscriptions. The deletion is performed
        /// by the server, and so has no immediate impact on the contents of the local Realm. If the
        /// device is currently offline, the removal will not be processed until the device returns online.
        /// </summary>
        /// <typeparam name="T">The type of the objects that make up the subscription query.</typeparam>
        /// <param name="subscription">The subscription to cancel.</param>
        /// <returns>An awaitable task, that indicates that the subscription has been removed locally.</returns>
        public static async Task UnsubscribeAsync <T>(this Subscription <T> subscription)
        {
            Argument.NotNull(subscription, nameof(subscription));
            if (subscription.State == SubscriptionState.Invalidated)
            {
                return;
            }

            AsyncHelper.EnsureValidContext();

            subscription.Handle.Unsubscribe();

            var tcs = new TaskCompletionSource <object>();
            PropertyChangedEventHandler handler = null;

            handler = new PropertyChangedEventHandler((s, e) =>
            {
                switch (subscription.State)
                {
                case SubscriptionState.Invalidated:
                    tcs.TrySetResult(null);
                    break;

                case SubscriptionState.Error:
                    tcs.TrySetException(subscription.Error);
                    break;
                }
            });

            subscription.PropertyChanged += handler;
            try
            {
                await tcs.Task;
            }
            finally
            {
                subscription.PropertyChanged -= handler;
                subscription.SubscriptionToken.Dispose();
            }
        }