/// <summary> /// Creates a new running task /// </summary> public static UnityTask RunOnMain <TP>(Action <TP> action, TP param) { var task = new UnityTask(action, param, TaskStrategy.MainThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask RunCoroutine(Func <IEnumerator> function) { var task = new UnityTask(function()); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask RunOnMain(Action action) { var task = new UnityTask(action, TaskStrategy.MainThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask RunOnCurrent(Action action) { var task = new UnityTask(action, TaskStrategy.CurrentThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask Run(Action action) { var task = new UnityTask(action); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask RunOnCurrent <TParam>(Action <TParam> action, TParam param) { var task = new UnityTask(action, param, TaskStrategy.CurrentThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask <TResult> RunOnMain <TResult>(Func <TResult> function) { var task = new UnityTask <TResult>(function, TaskStrategy.MainThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask <TResult> Run <TParam, TResult>(Func <TParam, TResult> function, TParam param) { var task = new UnityTask <TResult>(function, param); task.Start(); return(task); }
IEnumerator Test8(UnityTask <string> UnityTask) { yield return(1); Counter++; UnityTask.Result = "8 Coroutine With Result"; }
IEnumerator Test9(UnityTask <string> UnityTask) { yield return(1); UnityTask.Result = ("9 Coroutine with UnityTask State Complete"); Counter++; }
/// <summary> /// Creates a new running task /// </summary> public static UnityTask <TResult> Run <TResult>(Func <TResult> function) { var task = new UnityTask <TResult>(function); task.Start(); return(task); }
IEnumerator Test5(UnityTask UnityTask) { yield return(1); Counter++; Debug.Log("5 Coroutine with UnityTask"); }
public IEnumerator Start() { Application.logMessageReceived += Application_logMessageReceived; yield return(1); Debug.Log("Tests (9)"); UnityTask.Run(() => Debug.Log("1 Run Complete")); yield return(new WaitForSeconds(1)); UnityTask.Run(Test2, "2 Run With Param Complete"); yield return(new WaitForSeconds(1)); UnityTask.RunCoroutine(Test3); yield return(new WaitForSeconds(1)); UnityTask.RunCoroutine(Test4()).ContinueWith(t => Debug.Log("4 complete")); yield return(new WaitForSeconds(1)); UnityTask.RunCoroutine(Test5).ContinueWith(t => Debug.Log("5 complete")); yield return(new WaitForSeconds(1)); UnityTask.Run(() => { return("6 Run with Result Complete"); }).ContinueWith(t => Debug.Log(t.Result)); yield return(new WaitForSeconds(1)); UnityTask.Run <string, string>(Test7, "7 Run with Param and Result").ContinueWith(t => Debug.Log(t.Result)); yield return(new WaitForSeconds(1)); var t1 = UnityTask.RunCoroutine <string>(Test8); yield return(new WaitForSeconds(1)); Debug.Log(t1.Result); UnityTask.RunCoroutine <string>(Test9).ContinueWith(t => Debug.Log(t.Result)); }
void BackgroundToBackgroundException() { var task1 = UnityTask.Run(() => { Debug.Log("1 Go"); var task2 = UnityTask.Run(() => { UnityTask.Delay(100); Debug.Log("2 Go"); throw new Exception("2 Fail"); }); task2.Wait(); if (task2.IsFaulted) { throw task2.Exception; } }); task1.Wait(); Debug.Log(task1.Status + " " + task1.Exception.Message); }
/// <summary> /// Creates a new running task on the current thread that returns a result /// </summary> public static UnityTask <TResult> RunOnCurrent <TParam, TResult>(Func <TParam, TResult> function, TParam param) { var task = new UnityTask <TResult>(function, param, TaskStrategy.CurrentThread); task.Start(); return(task); }
/// <summary> /// Creates a new running task that returns a result /// </summary> public static UnityTask <TResult> RunCoroutine <TResult>(IEnumerator function) { var task = new UnityTask <TResult>(function); task.Start(); return(task); }
IEnumerator Test8(UnityTask <string> UnityTask) { yield return(1); Debug.Log("8 Coroutine With Result..."); //set result or exception UnityTask.Result = "8 Complete"; }
public static Action <Response> FromResponse(this UnityTask task) { return((response) => { task.Metadata = response.Metadata; task.Complete(response.Exception); }); }
void Background() { UnityTask.Run(() => { Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); }
void MainTest() { UnityTask.RunOnMain(() => { Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); }
/// <summary> /// Creates a new running task which passes the task as a parameter /// </summary> public static UnityTask RunCoroutine(Func <UnityTask, IEnumerator> function) { var task = new UnityTask(); task.Strategy = TaskStrategy.Coroutine; task._routine = function(task); task.Start(); return(task); }
/// <summary> /// Creates a new running task which passes the task as a parameter, and three additional parameters /// </summary> public static UnityTask RunCoroutine <TParam1, TParam2, TParam3>(Func <UnityTask, TParam1, TParam2, TParam3, IEnumerator> function, TParam1 param1, TParam2 param2, TParam3 param3) { var task = new UnityTask(); task.Strategy = TaskStrategy.Coroutine; task._routine = function(task, param1, param2, param3); task.Start(); return(task); }
/// <summary> /// Creates a task which returns a result, passes the task as a parameter, and passes two additional parameters /// </summary> public static UnityTask <TResult> RunCoroutine <TParam1, TParam2, TResult>(Func <UnityTask <TResult>, TParam1, TParam2, IEnumerator> function, TParam1 param1, TParam2 param2) { var task = new UnityTask <TResult>(); task.Strategy = TaskStrategy.Coroutine; task.Paramater = task; task._routine = function(task, param1, param2); task.Start(); return(task); }
IEnumerator Test5(UnityTask UnityTask) { yield return(1); if (UnityTask == null) { Debug.LogWarning("wtf"); } Debug.Log("5 Coroutine with UnityTask State Complete"); }
/// <summary> /// Waits for the task to complete /// </summary> public static T Wait <T>(this T self) where T : UnityTask { UnityTask.Delay(10); while (self.keepWaiting) { UnityTask.Delay(10); } return(self); }
private IEnumerator ConvertToAsync <T>(UnityTask <T> task, Func <UnityTask <TResult>, T> func) { while (!IsCompleted) { yield return(1); } task.Result = func(this); task.Exception = Exception; task.Status = Status; }
void BackgroundException() { var task1 = UnityTask.Run(() => { throw new Exception("Hello World"); }); task1.Wait(); Debug.Log(task1.Status + " " + task1.Exception.Message); }
IEnumerator Test9(UnityTask <string> UnityTask) { yield return(1); if (UnityTask == null) { Debug.LogWarning("wtf"); } UnityTask.Result = ("9 Coroutine with UnityTask State Complete"); }
static IEnumerator TimeOutAsync(UnityTask task, int seconds, Action <UnityTask> onTimeout = null) { yield return(new WaitForSeconds(seconds)); if (task.IsRunning) { if (onTimeout != null) { onTimeout(task); } task.Complete(new Exception("Timeout")); } }
public static Action <Response <T> > FromResponse <T>(this UnityTask <T> task) { return((response) => { task.Metadata = response.Metadata; if (response.IsFaulted) { task.Complete(response.Exception); } else { task.Complete(response.Result); } }); }
/// <summary> /// Begins unsubscription to the ORTC channel /// </summary> /// <param name="channel"></param> /// <returns>A task for the duration of the process</returns> public UnityTask Unsubscribe(string channel) { if (State != ConnectionState.Connected) { return UnityTask.FailedTask(new Exception("Not connected")); } if (GetSubscriptionState(channel) != SubscriptionState.Subscribed) { return UnityTask.FailedTask(new Exception("Not subscribed")); } _unsubscribeTask = new UnityTask(TaskStrategy.Custom); _lastUnsubscribeChannel = channel; _client.Unsubscribe(channel); return _unsubscribeTask; }
/// <summary> /// Begins subscription to the ORTC channel /// </summary> /// <param name="channel"></param> /// <returns>A task for the duration of the process</returns> public UnityTask Subscribe(string channel) { if (State != ConnectionState.Connected) { return UnityTask.FailedTask(new Exception("Not Connected")); } var s = GetSubscriptionState(channel); if (s != SubscriptionState.Unsubscribed) { return UnityTask.FailedTask(new Exception("Already subscribed or is Subscribing")); } _subscribeTask = new UnityTask(TaskStrategy.Custom); _lastSubscribeChannel = channel; _client.Subscribe(channel, _client_OnMessage); return _subscribeTask; }
IEnumerator Test8(UnityTask<string> UnityTask) { yield return 1; Counter++; UnityTask.Result = "8 Coroutine With Result"; }
/// <summary> /// Requests a new guest account. Use for 'Skip Sign In' option. /// </summary> /// <returns></returns> public UnityTask Guest() { var task = new UnityTask(TaskStrategy.Custom); Guest(task.FromResponse()); return task; }
IEnumerator GetPresenceAsync(UnityTask<Presence> task) { var btask = BalancerClient.GetServerUrl(Url, IsCluster, ApplicationKey); yield return TaskManager.StartRoutine(btask.WaitRoutine()); if (btask.IsFaulted) { task.Exception = btask.Exception; task.Status = TaskStatus.Faulted; yield break; } var server = btask.Result; var presenceUrl = String.IsNullOrEmpty(server) ? server : server[server.Length - 1] == '/' ? server : server + "/"; presenceUrl = String.Format("{0}presence/{1}/{2}/{3}", presenceUrl, ApplicationKey, AuthenticationToken, Channel); var htask = HttpClient.GetAsync(presenceUrl); yield return TaskManager.StartRoutine(htask.WaitRoutine()); if (htask.IsFaulted) { task.Exception = htask.Exception; task.Status = TaskStatus.Faulted; yield break; } task.Result = Deserialize(htask.Content); }
IEnumerator CoroutineUnityTaskStateAsync(UnityTask<string> UnityTask) { yield return 1; UnityTask.Result = "Hello World"; }
/// <summary> /// Begins Disconnection /// </summary> /// <returns>A task for the duration of the process</returns> public UnityTask Disconnect() { if (State == ConnectionState.Disconnected) { return UnityTask.FailedTask(new Exception("The client is already disconnected")); } var disconnect = new UnityTask(TaskStrategy.Custom); _client.Disconnect(); SubscriptionStates.Clear(); disconnect.Status = TaskStatus.Success; return disconnect; }
IEnumerator GetServerFromBalancerAsync(UnityTask<string> task) { var parsedUrl = String.IsNullOrEmpty(ApplicationKey) ? Url : Url + "?appkey=" + ApplicationKey; var innerTask = Client.GetAsync(parsedUrl); yield return TaskManager.StartRoutine(innerTask.WaitRoutine()); if (innerTask.IsFaulted) { task.Exception = innerTask.Exception; task.Status = TaskStatus.Faulted; yield break; } task.Result = ParseBalancerResponse(innerTask.Content); }
IEnumerator PostAuthenticationAsync(UnityTask<bool> task) { var connectionUrl = Url; if (IsCluster) { var cTask = ClusterClient.GetClusterServerWithRetry(Url, ApplicationKey); yield return TaskManager.StartRoutine(cTask.WaitRoutine()); if (cTask.IsFaulted) { task.Exception = cTask.Exception; task.Status = TaskStatus.Faulted; yield break; } connectionUrl = cTask.Result; } connectionUrl = connectionUrl[connectionUrl.Length - 1] == '/' ? connectionUrl : connectionUrl + "/"; var postParameters = String.Format("AT={0}&PVT={1}&AK={2}&TTL={3}&PK={4}", AuthenticationToken, AuthenticationTokenIsPrivate ? 1 : 0, ApplicationKey, TimeToLive, PrivateKey); if (Permissions != null && Permissions.Count > 0) { postParameters += String.Format("&TP={0}", Permissions.Count); foreach (var permission in Permissions) { var permissionItemText = String.Format("{0}=", permission.Key); var list = new List<ChannelPermissions>(permission.Value); foreach (var permissionItemValue in list) { permissionItemText += ((char)permissionItemValue).ToString(); } postParameters += String.Format("&{0}", permissionItemText); } } var hTask = Client.PostAsync(String.Format("{0}authenticate", connectionUrl), postParameters); yield return TaskManager.StartRoutine(hTask.WaitRoutine()); if (hTask.IsFaulted) { task.Exception = hTask.Exception; task.Status = TaskStatus.Faulted; yield break; } if (hTask.StatusCode == HttpStatusCode.Unauthorized) { task.Exception = new OrtcException(OrtcExceptionReason.Unauthorized, String.Format("Unable to connect to the authentication server {0}.", connectionUrl)); task.Status = TaskStatus.Faulted; yield break; } task.Result = hTask.IsSuccess; }
/// <summary> /// Begins a Resume Task. /// Will reconnect and reapply paused subscriptions /// </summary> /// <returns>A task for the duration of the process</returns> public UnityTask Resume() { if (State != ConnectionState.Paused) { return UnityTask.FailedTask(new Exception("The client is not paused")); } State = ConnectionState.Resuming; // var task = _connectionTask = new UnityTask(TaskStrategy.Custom); _client.Connect(ApplicationKey, AuthenticationToken); return task; }
/// <summary> /// Removal /// </summary> /// <returns></returns> public UnityTask FacebookDisconnect() { var task = new UnityTask { Strategy = TaskStrategy.Custom }; FacebookDisconnect(task.FromResponse()); return task; }
/// <summary> /// Sign in request /// </summary> /// <param name="token"></param> /// <returns></returns> public UnityTask FacebookConnect(AccessToken token) { var task = new UnityTask { Strategy = TaskStrategy.Custom }; FacebookConnect(token, task.FromResponse()); return task; }
/// <summary> /// Deletes the current account /// </summary> /// <param name="password"></param> /// <returns></returns> public UnityTask Delete(string password) { var task = new UnityTask(TaskStrategy.Custom); Delete(password, task.FromResponse()); return task; }
/// <summary> /// Tells the server to send out an recovery email. This email will contain a reset token. /// </summary> /// <param name="email"></param> /// <returns></returns> public UnityTask Reset(string email) { var task = new UnityTask(TaskStrategy.Custom); Reset(email, task.FromResponse()); return task; }
/// <summary> /// Update account details /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public UnityTask Update(string email, string password) { var task = new UnityTask(TaskStrategy.Custom); Update(email, password, task.FromResponse()); return task; }
/// <summary> /// Disconnects but caches subscriptions. Call Resume to resubscribe from cache. /// </summary> /// <returns>A task for the duration of the process</returns> public UnityTask Pause() { if (State == ConnectionState.Paused || State == ConnectionState.Pausing) { return UnityTask.FailedTask(new Exception("The client is already paused or pausing")); } if (State == ConnectionState.Disconnected || State == ConnectionState.Disconnected) { return UnityTask.FailedTask(new Exception("The client is already disconnected")); } State = ConnectionState.Pausing; var disconnect = new UnityTask(TaskStrategy.Custom); _client.Disconnect(); foreach (var state in SubscriptionStates.Keys.ToArray()) { SubscriptionStates[state] = SubscriptionState.Paused; } State = ConnectionState.Paused; disconnect.Status = TaskStatus.Success; return disconnect; }
IEnumerator TaskAsync(UnityTask task, bool hault = true) { yield return 1; yield return task; if (task.IsFaulted) { if (task.Exception is HttpException) { var hte = task.Exception as HttpException; foreach (var error in hte.GetErrors()) { Debug.LogError(error); } } else { Debug.LogError(task.Exception.Message); } if (hault) { Debug.LogError("Haulting"); StopAllCoroutines(); while (true) { yield return 1; } } } yield return 1; }
/// <summary> /// Begins a Connection Task. /// Be sure to set your AuthenticationToken and Metadata First ! /// </summary> /// <returns>A task for the duration of the process</returns> public UnityTask Connect() { if (State == ConnectionState.Connecting) { return _connectionTask; } if (State != ConnectionState.Disconnected && State != ConnectionState.Paused) { return UnityTask.FailedTask(new Exception("Already Connected")); } if (State == ConnectionState.Paused) { State = ConnectionState.Disconnected; SubscriptionStates.Clear(); } _connectionTask = new UnityTask(TaskStrategy.Custom); State = ConnectionState.Connecting; _client.Connect(ApplicationKey, AuthenticationToken); return _connectionTask; }
IEnumerator GetClusterServerWithRetryAsync(UnityTask<string> task) { int currentAttempts; for (currentAttempts = 0;currentAttempts <= MaxConnectionAttempts;currentAttempts++) { var innerTask = GetClusterServer(); yield return TaskManager.StartRoutine(innerTask.WaitRoutine()); task.Result = innerTask.Result; if (innerTask.IsSuccess && !String.IsNullOrEmpty(task.Result)) { yield break; } currentAttempts++; if (currentAttempts > MaxConnectionAttempts) { task.Exception = new OrtcException(OrtcExceptionReason.ConnectionError, "Unable to connect to the authentication server."); task.Status = TaskStatus.Faulted; yield break; } yield return TaskManager.WaitForSeconds(RetryThreadSleep); } }
IEnumerator EnablePresenceAsync(UnityTask<string> task) { var btask = BalancerClient.GetServerUrl(Url, IsCluster, ApplicationKey); yield return TaskManager.StartRoutine(btask.WaitRoutine()); if (btask.IsFaulted) { task.Exception = btask.Exception; task.Status = TaskStatus.Faulted; yield break; } var server = btask.Result; var presenceUrl = String.IsNullOrEmpty(server) ? server : server[server.Length - 1] == '/' ? server : server + "/"; presenceUrl = String.Format("{0}presence/enable/{1}/{2}", presenceUrl, ApplicationKey, Channel); var content = String.Format("privatekey={0}", PrivateKey); if (MetaData) { content = String.Format("{0}&metadata=1", content); } var htask = HttpClient.PostAsync(presenceUrl, content); yield return TaskManager.StartRoutine(htask.WaitRoutine()); if (htask.IsFaulted) { task.Exception = htask.Exception; task.Status = TaskStatus.Faulted; yield break; } task.Result = htask.Content; }
IEnumerator GetAsync(UnityTask<string> task) { var clusterRequestParameter = !String.IsNullOrEmpty(ApplicationKey) ? String.Format("appkey={0}", ApplicationKey) : String.Empty; var clusterUrl = String.Format("{0}{1}?{2}", Url, !String.IsNullOrEmpty(Url) && Url[Url.Length - 1] != '/' ? "/" : String.Empty, clusterRequestParameter); var hTask = Client.GetAsync(clusterUrl); yield return TaskManager.StartRoutine(hTask.WaitRoutine()); if (hTask.IsFaulted) { task.Exception = hTask.Exception; task.Status = TaskStatus.Faulted; yield break; } task.Result = ParseResponse(hTask.Content); }
IEnumerator DemoCoroutineWithResult(UnityTask<string> task) { yield return 1; Counter++; task.Result = "Hello"; }
IEnumerator SendMessageAsync(UnityTask<bool> task) { var connectionUrl = Url; if (IsCluster) { var cTask = ClusterClient.GetClusterServerWithRetry(Url, ApplicationKey); yield return TaskManager.StartRoutine(cTask.WaitRoutine()); if (cTask.IsFaulted) { task.Exception = cTask.Exception; task.Status = TaskStatus.Faulted; yield break; } connectionUrl = cTask.Result; } connectionUrl = connectionUrl.Last() == '/' ? connectionUrl : connectionUrl + "/"; var postParameters = String.Format("AT={0}&AK={1}&PK={2}&C={3}&M={4}", AuthenticationToken, ApplicationKey, PrivateKey, Channel, HttpUtility.UrlEncode(Message)); var hTask = Client.PostAsync(String.Format("{0}send", connectionUrl), postParameters); yield return TaskManager.StartRoutine(hTask.WaitRoutine()); if (hTask.IsFaulted) { task.Exception = hTask.Exception; task.Status = TaskStatus.Faulted; yield break; } task.Result = hTask.StatusCode == HttpStatusCode.Created; }
IEnumerator Test5(UnityTask UnityTask) { yield return 1; Counter++; Debug.Log("5 Coroutine with UnityTask"); }
void _client_OnUnsubscribed(string channel) { if (!SubscriptionStates.ContainsKey(channel)) SubscriptionStates.Add(channel, SubscriptionState.Unsubscribed); else SubscriptionStates[channel] = SubscriptionState.Unsubscribed; if (_unsubscribeTask != null) { _unsubscribeTask.Status = TaskStatus.Success; _unsubscribeTask = null; } }
IEnumerator Test9(UnityTask<string> UnityTask) { yield return 1; UnityTask.Result = ("9 Coroutine with UnityTask State Complete"); Counter++; }
/// <summary> /// New account created in memory /// </summary> /// <returns>Realtime Authentication Token to use</returns> public UnityTask<RealtimeToken> SignIn(Dictionary<string, string[]> channels = null) { var task = new UnityTask<RealtimeToken>(TaskStrategy.Custom); SignIn(channels, task.FromResponse()); return task; }