Example #1
0
			public void OnError(Exception error) {
				try {
					promise.TrySetException(error);
				} finally {
					registration.Dispose();
					disposable.Dispose();
				}
			}
Example #2
0
    public static UniTask <T> .Awaiter GetAwaiter <T>(this AsyncOperationHandle <T> asset)
    {
        UniTaskCompletionSource <T> completionSource = new UniTaskCompletionSource <T>();

        asset.Completed += (result) =>
        {
            switch (result.Status)
            {
            case AsyncOperationStatus.None:
                break;

            case AsyncOperationStatus.Succeeded:
                completionSource.TrySetResult(result.Result);
                break;

            case AsyncOperationStatus.Failed:
                completionSource.TrySetException(result.OperationException);
                break;

            default:
                throw new ArgumentOutOfRangeException(result.OperationException.ToString());
            }
            // completionSource.TrySetResult(result.Result);
        };
        return(completionSource.Task.GetAwaiter());
    }
Example #3
0
        public async UniTask <int> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
#if NET5_0_OR_GREATER
            var xs = new ArraySegment <byte>(buffer, offset, count);
            var i  = await socket.ReceiveAsync(xs, SocketFlags.None, cancellationToken).ConfigureAwait(false);

            return(i);
#else
            var tcs = new UniTaskCompletionSource <int>();

            socket.BeginReceive(buffer, offset, count, SocketFlags.None, x =>
            {
                int i;
                try
                {
                    i = socket.EndReceive(x);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                    return;
                }
                tcs.TrySetResult(i);
            }, null);

            return(await tcs.Task);
#endif
        }
Example #4
0
        public async UniTask <ReadOnlyMemory <byte> > ReceiveAsync(CancellationToken cancellationToken)
        {
#if NET5_0_OR_GREATER
            var i = await socket.ReceiveAsync(buffer, SocketFlags.None, cancellationToken).ConfigureAwait(false);

            return(buffer.AsMemory(0, i));
#else
            var tcs = new UniTaskCompletionSource <ReadOnlyMemory <byte> >();

            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, x =>
            {
                int i;
                try
                {
                    i = socket.EndReceive(x);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                    return;
                }
                var r = buffer.AsMemory(0, i);
                tcs.TrySetResult(r);
            }, null);

            return(await tcs.Task);
#endif
        }
Example #5
0
    private UniTask <LoginResult> TryLoginDefaultAsync()
    {
        // WebGL では端末 ID 的なものがなく、スコアランキング程度で Facebook 等連携してもらうのもユーザに手間をかけるので、
        // 簡易な端末 ID もどきとして。
        var guid = PlayerPrefs.GetString(GuidKey);

        if (string.IsNullOrEmpty(guid))
        {
            guid = Guid.NewGuid().ToString("D");
            PlayerPrefs.SetString(GuidKey, guid);
            PlayerPrefs.Save();
        }

        Debug.Log(guid);

        var request = new LoginWithCustomIDRequest
        {
            CustomId      = guid,
            CreateAccount = true
        };

        var source = new UniTaskCompletionSource <LoginResult>();
        Action <LoginResult>  resultCallback = (_result) => source.TrySetResult(_result);
        Action <PlayFabError> errorCallback  = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.LoginWithCustomID(request, resultCallback, errorCallback);
        return(source.Task);
    }
Example #6
0
        public UniTask <int> SendAsync(byte[] buffer, CancellationToken cancellationToken = default)
        {
#if NET5_0_OR_GREATER
            return(socket.SendAsync(buffer, SocketFlags.None, cancellationToken));
#else
            var tcs = new UniTaskCompletionSource <int>();
            socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, x =>
            {
                int i;
                try
                {
                    i = socket.EndSend(x);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                    return;
                }
                tcs.TrySetResult(i);
            }, null);
#if !UNITY_2018_3_OR_NEWER
            return(new UniTask <int>(tcs.Task));
#else
            return(tcs.Task);
#endif
#endif
        }
Example #7
0
        public UniTask <ReadLocalFileResult> ReadLocalFile(string localSubPath)
        {
            var source = new UniTaskCompletionSource <ReadLocalFileResult>();

            ReadLocalFile(localSubPath,
                          result => source.TrySetResult(result),
                          error => source.TrySetException(error)
                          );
            return(source.Task);
        }
Example #8
0
        public UniTask <bool> UpdateFile(string localSubPath, string remoteSubPath)
        {
            var source = new UniTaskCompletionSource <bool>();

            UpdateFile(localSubPath, remoteSubPath,
                       result => source.TrySetResult(result),
                       error => source.TrySetException(error)
                       );
            return(source.Task);
        }
Example #9
0
        public UniTask <byte[]> Download(string url)
        {
            var task = new UniTaskCompletionSource <byte[]>();

            Download(url,
                     response => task.TrySetResult(response),
                     error => task.TrySetException(error)
                     );
            return(task.Task);
        }
Example #10
0
        public override UniTask Free(string location, Texture2DCompression compression, Picture instance)
        {
            var source = new UniTaskCompletionSource <bool>();

            Free(location, compression, instance,
                 () => source.TrySetResult(true),
                 exception => source.TrySetException(exception)
                 );
            return(source.Task);
        }
Example #11
0
        // WRITE
        public UniTask WriteLocalFile(string subPath, byte[] bytes, string version)
        {
            var source = new UniTaskCompletionSource();

            WriteLocalFile(subPath, bytes, version,
                           () => source.TrySetResult(),
                           error => source.TrySetException(error)
                           );
            return(source.Task);
        }
Example #12
0
        // DELETE
        public UniTask <bool> DeleteLocalFile(string subPath)
        {
            var source = new UniTaskCompletionSource <bool>();

            DeleteLocalFile(subPath,
                            result => source.TrySetResult(result),
                            error => source.TrySetException(error)
                            );
            return(source.Task);
        }
Example #13
0
            public UniTask <string> GetVersionFileName(string fileName)
            {
                var source = new UniTaskCompletionSource <string>();

                versionFileNomenclatureMethod(fileName,
                                              result => source.TrySetResult(result),
                                              error => source.TrySetException(error)
                                              );
                return(source.Task);
            }
Example #14
0
        // ================================================
        // INITIALIZATION
        // ================================================
        public UniTask Init(object[] data)
        {
            var source = new UniTaskCompletionSource();

            Init(data,
                 () => source.TrySetResult(),
                 error => source.TrySetException(error)
                 );
            return(source.Task);
        }
Example #15
0
        public UniTask SetLocalVersion(string subPath, string version)
        {
            var source = new UniTaskCompletionSource();

            SetLocalVersion(subPath, version,
                            () => source.TrySetResult(),
                            error => source.TrySetException(error)
                            );
            return(source.Task);
        }
Example #16
0
        /// <summary>
        /// Downloads an image form the URL and returns the results using UniTask
        /// </summary>
        /// <param name="path"></param>
        /// <returns>A UniTask<Texture2D> instance</Texture2D></returns>
        public UniTask <Texture2D> Download(string path)
        {
            var source = new UniTaskCompletionSource <Texture2D>();

            Download(path,
                     result => source.TrySetResult(result),
                     exception => source.TrySetException(exception)
                     );
            return(source.Task);
        }
Example #17
0
        public override UniTask <Sprite> Get(string location, Texture2DCompression compression, Picture instance)
        {
            var source = new UniTaskCompletionSource <Sprite>();

            Get(location, compression, instance,
                result => source.TrySetResult(result),
                exception => source.TrySetException(exception)
                );
            return(source.Task);
        }
Example #18
0
        // ================================================
        // LOCAL VERSION
        // ================================================
        #region LOCAL_VERSION
        public UniTask <string> GetLocalVersion(string subPath)
        {
            var source = new UniTaskCompletionSource <string>();

            GetLocalVersion(subPath,
                            result => source.TrySetResult(result),
                            error => source.TrySetException(error)
                            );
            return(source.Task);
        }
Example #19
0
		public void SetException(Exception exception) {
			if (promise == null) {
				promise = new UniTaskCompletionSource();
			}

			if (exception is OperationCanceledException ex) {
				promise.TrySetCanceled(ex);
			} else {
				promise.TrySetException(exception);
			}
		}
Example #20
0
        void ConnectAndReceiveLoop(Uri uri)
        {
            // connect and handshake
            try
            {
                Connect(uri);
                connectCompletionSource.TrySetResult();

                var sendThread = new Thread(() =>
                {
                    SendLoop.Loop(sendQueue, stream, cancellationTokenSource.Token);
                })
                {
                    IsBackground = true
                };
                sendThread.Start();

                while (true)
                {
                    MemoryStream message = Parser.ReadOneMessage(stream);
                    receiveQueue.Writer.TryWrite(message);
                }
            }
            catch (EndOfStreamException)
            {
                connectCompletionSource.TrySetResult();
                receiveQueue.Writer.TryComplete();
            }
            catch (Exception e)
            {
                connectCompletionSource.TrySetException(e);
            }
            finally
            {
                cancellationTokenSource.Cancel();
                stream?.Close();
                client?.Close();
            }
        }
Example #21
0
    public static UniTask <UpdateUserTitleDisplayNameResult> UpdateUserTitleDisplayNameAsync(string displayName)
    {
        var request = new UpdateUserTitleDisplayNameRequest
        {
            DisplayName = displayName
        };

        var source = new UniTaskCompletionSource <UpdateUserTitleDisplayNameResult>();
        Action <UpdateUserTitleDisplayNameResult> resultCallback = (_result) => source.TrySetResult(_result);
        Action <PlayFabError> errorCallback = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.UpdateUserTitleDisplayName(request, resultCallback, errorCallback);
        return(source.Task);
    }
    public UniTask <GetTitleDataResult> TryGetDataAsync()
    {
        var source = new UniTaskCompletionSource <GetTitleDataResult>();
        Action <GetTitleDataResult> resultCallback = (_result) =>
        {
            result = _result;
            Debug.Log(Dump());
            source.TrySetResult(_result);
        };
        Action <PlayFabError> errorCallback = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.GetTitleData(new GetTitleDataRequest(), resultCallback, errorCallback);
        return(source.Task);
    }
Example #23
0
        public async Task SetFirst()
        {
            {
                var tcs = new UniTaskCompletionSource <int>();

                tcs.TrySetResult(10);
                var a = await tcs.Task; // ok.
                var b = await tcs.Task; // ok.
                a.Should().Be(10);
                b.Should().Be(10);
                tcs.Task.Status.Should().Be(UniTaskStatus.Succeeded);
            }

            {
                var tcs = new UniTaskCompletionSource <int>();

                tcs.TrySetException(new TestException());

                await Assert.ThrowsAsync <TestException>(async() => await tcs.Task);

                await Assert.ThrowsAsync <TestException>(async() => await tcs.Task);

                tcs.Task.Status.Should().Be(UniTaskStatus.Faulted);
            }

            var cts = new CancellationTokenSource();

            {
                var tcs = new UniTaskCompletionSource <int>();

                tcs.TrySetException(new OperationCanceledException(cts.Token));

                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);

                tcs.Task.Status.Should().Be(UniTaskStatus.Canceled);
            }

            {
                var tcs = new UniTaskCompletionSource <int>();

                tcs.TrySetCanceled(cts.Token);

                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);

                tcs.Task.Status.Should().Be(UniTaskStatus.Canceled);
            }
        }
Example #24
0
		public static UniTask<T> ToUniTask<T>(this IObservable<T> source, CancellationToken cancellationToken = default(CancellationToken), bool useFirstValue = false) {
			var promise = new UniTaskCompletionSource<T>();
			var disposable = new SingleAssignmentDisposable();

			var observer = useFirstValue
						   ? (IObserver<T>)new FirstValueToUniTaskObserver<T>(promise, disposable, cancellationToken)
						   : (IObserver<T>)new ToUniTaskObserver<T>(promise, disposable, cancellationToken);

			try {
				disposable.Disposable = source.Subscribe(observer);
			} catch (Exception ex) {
				promise.TrySetException(ex);
			}

			return promise.Task;
		}
Example #25
0
    public static UniTask <List <PlayerLeaderboardEntry> > GetLeaderboardAsync(string statisticName, int maxResultsCount)
    {
        var request = new GetLeaderboardRequest
        {
            MaxResultsCount = maxResultsCount,
            StatisticName   = statisticName,
        };

        var source = new UniTaskCompletionSource <List <PlayerLeaderboardEntry> >();
        Action <GetLeaderboardResult> resultCallback = (_result) =>
        {
            DebugLogLeaderboard(_result);
            source.TrySetResult(_result.Leaderboard);
        };
        Action <PlayFabError> errorCallback = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.GetLeaderboard(request, resultCallback, errorCallback);
        return(source.Task);
    }
Example #26
0
        /// <summary>
        /// Returns the download URL for the content of the given key
        /// using the right CDN provider
        /// </summary>
        public UniTask <string> GetURL(string key)
        {
            var source = new UniTaskCompletionSource <string>();

            if (!key.StartsWith("/"))
            {
                key = "/" + key;
            }
            var url = PlayerIOClient.GameFS.GetUrl(key);

            if (string.IsNullOrEmpty(url))
            {
                source.TrySetException(new Exception("URL is null or empty"));
            }
            else
            {
                source.TrySetResult(url);
            }
            return(source.Task);
        }
Example #27
0
    public static UniTask <UpdatePlayerStatisticsResult> UpdatePlayerStatisticAsync(string statisticName, int value)
    {
        var request = new UpdatePlayerStatisticsRequest
        {
            Statistics = new List <StatisticUpdate>()
            {
                new StatisticUpdate {
                    StatisticName = statisticName,
                    Value         = value
                }
            }
        };

        var source = new UniTaskCompletionSource <UpdatePlayerStatisticsResult>();
        Action <UpdatePlayerStatisticsResult> resultCallback = (_result) => source.TrySetResult(_result);
        Action <PlayFabError> errorCallback = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.UpdatePlayerStatistics(request, resultCallback, errorCallback);
        return(source.Task);
    }
Example #28
0
            private void InitReceiveSettings()
            {
                _connection.On <bool, ThreadMessage[]>("EnterRoomResultAsync", (result, messages) =>
                {
                    if (result)
                    {
                        _wait.TrySetResult();
                    }
                    else
                    {
                        _wait.TrySetException(new Exception("Cannot enter thread room!"));
                    }
                });

                _connection.On <ThreadMessage>("ReceiveMessageFromServer", message =>
                {
                    if (!string.IsNullOrEmpty(message?.Message))
                    {
                        _messageSubject.OnNext(message.Message);
                    }
                });
            }
Example #29
0
    private UniTask <LoginResult> TryLoginAndroidAsync()
    {
        var unityPlayer     = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        var currentActivity = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity");
        var contentResolver = currentActivity.Call <AndroidJavaObject>("getContentResolver");
        var secure          = new AndroidJavaClass("android.provider.Settings$Secure");
        var androidId       = secure.CallStatic <string>("getString", contentResolver, "android_id");

        Debug.Log(androidId);

        var request = new LoginWithAndroidDeviceIDRequest
        {
            AndroidDeviceId = androidId,
            CreateAccount   = true
        };

        var source = new UniTaskCompletionSource <LoginResult>();
        Action <LoginResult>  resultCallback = (_result) => source.TrySetResult(_result);
        Action <PlayFabError> errorCallback  = (_error) => source.TrySetException(new Exception(_error.GenerateErrorReport()));

        PlayFabClientAPI.LoginWithAndroidDeviceID(request, resultCallback, errorCallback);
        return(source.Task);
    }
Example #30
0
        public async Task MultiTwo()
        {
            {
                var tcs = new UniTaskCompletionSource <int>();

                async UniTask <int> Await()
                {
                    return(await tcs.Task);
                }

                var a = Await();
                var b = Await();
                var c = Await();
                tcs.TrySetResult(10);
                var r1 = await a;
                var r2 = await b;
                var r3 = await c;
                var r4 = await tcs.Task; // ok.
                (r1, r2, r3, r4).Should().Be((10, 10, 10, 10));
                tcs.Task.Status.Should().Be(UniTaskStatus.Succeeded);
            }

            {
                var tcs = new UniTaskCompletionSource <int>();

                async UniTask <int> Await()
                {
                    return(await tcs.Task);
                }

                var a = Await();
                var b = Await();
                var c = Await();

                tcs.TrySetException(new TestException());
                await Assert.ThrowsAsync <TestException>(async() => await a);

                await Assert.ThrowsAsync <TestException>(async() => await b);

                await Assert.ThrowsAsync <TestException>(async() => await c);

                await Assert.ThrowsAsync <TestException>(async() => await tcs.Task);

                tcs.Task.Status.Should().Be(UniTaskStatus.Faulted);
            }

            var cts = new CancellationTokenSource();

            {
                var tcs = new UniTaskCompletionSource <int>();

                async UniTask <int> Await()
                {
                    return(await tcs.Task);
                }

                var a = Await();
                var b = Await();
                var c = Await();

                tcs.TrySetException(new OperationCanceledException(cts.Token));
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await a)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await b)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await c)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);
                tcs.Task.Status.Should().Be(UniTaskStatus.Canceled);
            }
            {
                var tcs = new UniTaskCompletionSource <int>();

                async UniTask <int> Await()
                {
                    return(await tcs.Task);
                }

                var a = Await();
                var b = Await();
                var c = Await();

                tcs.TrySetCanceled(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await a)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await b)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await c)).CancellationToken.Should().Be(cts.Token);
                (await Assert.ThrowsAsync <OperationCanceledException>(async() => await tcs.Task)).CancellationToken.Should().Be(cts.Token);
                tcs.Task.Status.Should().Be(UniTaskStatus.Canceled);
            }
        }