Skip to content

Instantly share code, notes, and snippets.

@Naphier
Created May 4, 2017 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Naphier/44a63d8d07be52e589e387c642e572fd to your computer and use it in GitHub Desktop.
Save Naphier/44a63d8d07be52e589e387c642e572fd to your computer and use it in GitHub Desktop.
Example static start and finish request callbacks
//-----------------------------------------------------------------------
// <copyright file="HTTPRequest.cs" company="Mapbox">
// Copyright (c) 2016 Mapbox. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Mapbox.Unity
{
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public static class RequestCounter
{
public static int count = 0;
public static Action OnFirstRequest;
public static Action OnAllRequestsFinished;
}
internal sealed class HTTPRequest : IAsyncRequest
{
private readonly UnityWebRequest request;
private readonly Action<Response> callback;
public HTTPRequest(MonoBehaviour behaviour, string url, Action<Response> callback)
{
this.request = UnityWebRequest.Get(url);
this.callback = callback;
/*
if (url.Contains(".pbf"))
Debug.LogWarning("URL: " + url);
*/
behaviour.StartCoroutine(this.DoRequest());
if (RequestCounter.count == 0 &&
RequestCounter.OnFirstRequest != null)
RequestCounter.OnFirstRequest.Invoke();
RequestCounter.count++;
}
public void Cancel()
{
this.request.Abort();
}
private IEnumerator DoRequest()
{
yield return this.request.Send();
var response = new Response();
response.Error = this.request.error;
response.Data = this.request.downloadHandler.data;
this.callback(response);
RequestCounter.count--;
if (RequestCounter.count == 0 &&
RequestCounter.OnAllRequestsFinished != null)
RequestCounter.OnAllRequestsFinished.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment