How do you show iOS network indicator while TPL Task is running?

ios, task-parallel-library, xamarin, xamarin.ios

Solution

I created this class to wrap `NetworkActivityIndicatorVisible` into a pair of enter/leave methods.

public static class NetworkIndicator
{
    static int _counter;

    public static void EnterActivity ()
    {
        Interlocked.Increment (ref _counter);
        RefreshIndicator ();
    }

    public static void LeaveActivity ()
    {
        Interlocked.Decrement (ref _counter);
        RefreshIndicator ();
    }

    public static void AttachToTask (Task task)
    {
        if (task.IsCanceled || task.IsCanceled || task.IsFaulted)
            return;

        EnterActivity ();
        task.ContinueWith (t => {
            LeaveActivity ();
        });
    }

    static void RefreshIndicator ()
    {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible =
            (_counter > 0);
    }
}

Then I added two extension methods for convenience:

public static class TaskExtensions
{
    public static Task WithNetworkIndicator (this Task task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }

    public static Task<TResult> WithNetworkIndicator<TResult> (this Task<TResult> task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }
}

How I'm wrapping it:

var task = Api.QueryNotifications (AuthManager.CurrentProfile.Id, NotificationType.All, until, cached)
    .WithNetworkIndicator ();

Then I'm using the task as usual.

Problem

I'm heavily using Task Parallel Library when talking to server API. I would like to show iOS network indicator while any of these tasks is currently running. How do I go about that?

Original source