Esempio n. 1
0
        public async Task LazyImmediate()
        {
            {
                var l = UniTask.Lazy(() => UniTask.FromResult(1).AsUniTask());
                var a = AwaitAwait(l.Task);
                var b = AwaitAwait(l.Task);
                var c = AwaitAwait(l.Task);

                await a;
                await b;
                await c;
            }
            {
                var l = UniTask.Lazy(() => UniTask.FromException(new TaskTestException()));
                var a = AwaitAwait(l.Task);
                var b = AwaitAwait(l.Task);
                var c = AwaitAwait(l.Task);

                await Assert.ThrowsAsync <TaskTestException>(async() => await a);

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

                await Assert.ThrowsAsync <TaskTestException>(async() => await c);
            }
        }
Esempio n. 2
0
            protected override UniTask <BaseAbManifest> LoadManifestAsync(string url, int version, Func <string, UnityWebRequest> createFn)
            {
                BaseAbManifest manifest = loadManifestAsyncFake(url, version);

                A.CallTo(() => manifest.version).Returns(version);
                return(UniTask.FromResult(manifest));
            }
Esempio n. 3
0
        protected override UniTask <IReadOnlyDictionary <string, string[]> > LoadLocalizationAsync(Context context)
        {
            // Create the dictionary
            var localization = new Dictionary <string, string[]>();

            // Read the text data
            var loc = LoadArchiveFile <R1_PC_LocFile>(context, GetSpecialArchiveFilePath(context.Settings.EduVolume), R1_PC_ArchiveFileName.TEXT);

            // Save the localized name
            var locName = loc.LanguageNames[loc.LanguageUtilized];

            if (String.IsNullOrWhiteSpace(locName))
            {
                locName = context.Settings.EduVolume;
            }

            // Add the localization
            localization.Add($"TEXT ({locName})", loc.TextDefine.Select(x => x.Value).ToArray());

            // Read the general data
            var general = LoadArchiveFile <R1_PC_GeneralFile>(context, GetSpecialArchiveFilePath(context.Settings.EduVolume), R1_PC_ArchiveFileName.GENERAL);

            // Add the localization
            localization.Add($"GENERAL ({locName})", general.CreditsStringItems.Select(x => x.String.Value).ToArray());

            // Read the MOT data
            var mot = LoadArchiveFile <R1_PCEdu_MOTFile>(context, GetSpecialArchiveFilePath(context.Settings.EduVolume), R1_PC_ArchiveFileName.MOT);

            // Add the localization
            localization.Add($"MOT ({locName})", mot.TextDefine.Select(x => x.Value).ToArray());

            return(UniTask.FromResult <IReadOnlyDictionary <string, string[]> >(localization));
        }
Esempio n. 4
0
        public async Task LazyImmediate()
        {
            {
                var l = UniTask.Lazy(() => UniTask.FromResult(1));
                var a = AwaitAwait(l.Task);
                var b = AwaitAwait(l.Task);
                var c = AwaitAwait(l.Task);

                var a2 = await a;
                var b2 = await b;
                var c2 = await c;
                (a2, b2, c2).Should().Be((1, 1, 1));
            }
            {
                var l = UniTask.Lazy(() => UniTask.FromException <int>(new TaskTestException()));
                var a = AwaitAwait(l.Task);
                var b = AwaitAwait(l.Task);
                var c = AwaitAwait(l.Task);

                await Assert.ThrowsAsync <TaskTestException>(async() => await a);

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

                await Assert.ThrowsAsync <TaskTestException>(async() => await c);
            }
        }
    /// <summary>
    /// Save string data.
    /// </summary>
    /// <param name="key">data key.</param>
    /// <param name="data">data</param>
    /// <returns>Did overwrite value</returns>
    public override async UniTask <bool> SaveAsync(string key, string data)
    {
        bool hasKey = PlayerPrefs.HasKey(key);

        PlayerPrefs.SetString(key, data);

        return(await UniTask.FromResult(hasKey));
    }
Esempio n. 6
0
        public async Task ToAsyncEnumerableUniTask()
        {
            var t  = UniTask.FromResult(100);
            var xs = await t.ToUniTaskAsyncEnumerable().ToArrayAsync();

            xs.Length.Should().Be(1);
            xs[0].Should().Be(100);
        }
Esempio n. 7
0
        /// <summary>
        /// Is auto-renewable subscription's active.
        /// </summary>
        /// <param name="productId">Product ID.</param>
        /// <returns>returns true if the store receipt's expiration date is after the device's current time</returns>
        public async UniTask <bool> IsActiveSubscription(string productId)
        {
            var subInfo = GetSubscriptionInfo(productId);

            return(subInfo != null ?
                   await UniTask.FromResult(subInfo.isSubscribed() == Result.True) :
                   await UniTask.FromResult(false));
        }
        private void Start()
        {
            // 完了済みのUniTaskとして生成する
            var uniTask = new UniTask <int>(10);

            // UniTask.FromResult を用いても同じ
            var uniTask2 = UniTask.FromResult(10);
        }
        public async UniTask <bool> ExistsAsync(Uri uri, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }

            return(await UniTask.FromResult(File.Exists(GetUnescapedAbsolutePath(uri))));
        }
Esempio n. 10
0
        /// <summary>
        /// Gets introductory offer details.
        /// Includes Free Trial.
        /// </summary>
        /// <param name="productID">Product ID</param>
        /// <param name="groupProductIDs">Group products that productID belongs to.
        /// If empty or null, assume productID is in its own group.</param>
        /// <returns>Offer details if exists.</returns>
        public UniTask <IntroductoryOffer> GetIntroductoryOfferDetailsAsync(string productID, string[] groupProductIDs = null)
        {
            // Determine if product exists.
            var products = apple.GetProductDetails();

            if (products == null || !products.ContainsKey(productID))
            {
                // No product available.
                return(UniTask.FromResult <IntroductoryOffer>(null));
            }

            // Get product details.
            IntroductoryOffer offer = null;

            try {
                offer = new IOSIntroductoryOfferFactory(products[productID]).Make();
            } catch (InvalidOfferException) {
                // Invalid offer.
                return(UniTask.FromResult <IntroductoryOffer>(null));
            } catch (Exception e) {
                // Invalid json!
                Debug.LogWarning($"Invalid product data detected! {e.Message}");
                return(UniTask.FromResult <IntroductoryOffer>(null));
            }

            try {
                var          receiptData = System.Convert.FromBase64String(appleConfig.appReceipt);
                AppleReceipt receipt     = new AppleValidator(appleTangleData).Validate(receiptData);
                if (receipt == null || receipt.inAppPurchaseReceipts == null)
                {
                    // no previous subscription purchased.
                    return(UniTask.FromResult(offer));
                }

                if (groupProductIDs == null || groupProductIDs.Length == 0)
                {
                    groupProductIDs = new string[] { productID };
                }

                var prevCampaignPurchase = receipt.inAppPurchaseReceipts
                                           .FirstOrDefault(r =>
                                                           groupProductIDs.Contains(r.productID) &&
                                                           (r.isFreeTrial != 0 || r.isIntroductoryPricePeriod != 0));

                if (prevCampaignPurchase != null)
                {
                    // user already used free trial or introductory offer.
                    return(UniTask.FromResult <IntroductoryOffer>(null));
                }
            } catch {
                // unable to validate receipt or unable to access.
                return(UniTask.FromResult <IntroductoryOffer>(null));
            }

            return(UniTask.FromResult(offer));
        }
Esempio n. 11
0
        protected override void UpdateCommands(List <ILifeTimeCommand> nodeCommands)
        {
            base.UpdateCommands(nodeCommands);

            //create sync result for task
            var outputContextTarget = UniTask.FromResult <IContext>(PortPair.OutputPort);

            //create node commands
            nodeCommands.Add(new RegisterDataSourceCommand(outputContextTarget, contextDataSource));
        }
Esempio n. 12
0
        public UniTask <INetworkMessage> Call(INetworkMessage message, long sessionId)
        {
            var session = GetSession(sessionId);

            if (session != null)
            {
                return(session.Call(message));
            }
            return(UniTask.FromResult <INetworkMessage>(null));
        }
Esempio n. 13
0
        public IEnumerator WhenAny() => UniTask.ToCoroutine(async() =>
        {
            var a = UniTask.FromResult(999);
            var b = UniTask.Yield(PlayerLoopTiming.Update, CancellationToken.None).AsAsyncUnitUniTask();
            var c = UniTask.DelayFrame(99).AsAsyncUnitUniTask();

            var(win, a2, b2, c2) = await UniTask.WhenAny(a, b, c);
            win.Should().Be(0);
            a2.Should().Be(999);
        });
Esempio n. 14
0
        public IEnumerator WhenAll() => UniTask.ToCoroutine(async() =>
        {
            var a = UniTask.FromResult(999);
            var b = UniTask.Yield(PlayerLoopTiming.Update, CancellationToken.None).AsAsyncUnitUniTask();
            var c = UniTask.DelayFrame(99);

            var(a2, b2, c2) = await UniTask.WhenAll(a, b, c);
            a2.Is(999);
            b2.Is(AsyncUnit.Default);
            c2.Is(99);
        });
 public static UniTask <Result <T, E> > CheckIf <T, K, E>(this Result <T, E> result, Func <T, bool> predicate, Func <T, UniTask <Result <K, E> > > func)
 {
     if (result.IsSuccess && predicate(result.Value))
     {
         return(result.Check(func));
     }
     else
     {
         return(UniTask.FromResult(result));
     }
 }
Esempio n. 16
0
        async UniTask <T> IAsyncGetter.GetAsync <T>(string key, T defaultValue, Func <string, T> deserializeCallback, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (await((IAsyncChecker)this).HasAsync(key, cancellationToken))
            {
                return(await UniTask.FromResult((T)Storage[key]));
            }

            return(await UniTask.FromResult(defaultValue));
        }
Esempio n. 17
0
 static UniTask <T> RandomRun <T>(T value, CancellationToken ct)
 {
     if (Interlocked.Increment(ref rd) % 2 == 0)
     {
         return(UniTask.Run(() => value));
     }
     else
     {
         return(UniTask.FromResult(value));
     }
 }
Esempio n. 18
0
        UniTask <TValue> IFactory <TValue> .Create()
        {
            GameObject go   = GameObject.Instantiate(prefab);
            TValue     comp = go.GetComponent <TValue>();

            if (comp == null)
            {
                comp = go.AddComponent <TValue>();
            }
            return(UniTask.FromResult(comp));
        }
 /// <summary>
 ///     Executes the given action if the calling result is a success and condition is true. Returns the calling result.
 /// </summary>
 public static UniTask <Result <T, E> > TapIf <T, E>(this Result <T, E> result, bool condition, Func <T, UniTask> func)
 {
     if (condition)
     {
         return(result.Tap(func));
     }
     else
     {
         return(UniTask.FromResult(result));
     }
 }
 public static UniTask <Result <T> > CheckIf <T>(this Result <T> result, bool condition, Func <T, UniTask <Result> > func)
 {
     if (condition)
     {
         return(result.Check(func));
     }
     else
     {
         return(UniTask.FromResult(result));
     }
 }
        protected override void UpdateCommands(List <ILifeTimeCommand> nodeCommands)
        {
            base.UpdateCommands(nodeCommands);

            //create sync result for task
            var outputContextTask = UniTask.FromResult <IContext>(PortPair.OutputPort);
            //create node commands
            var sourceOutputPortCommand = new RegisterDataSourcesCommand <AssetReferenceDataSource>(outputContextTask, sources);

            nodeCommands.Add(sourceOutputPortCommand);
        }
Esempio n. 22
0
        public async UniTask <bool> ExistsAsync(Uri uri, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (Application.platform == RuntimePlatform.WebGLPlayer)
            {
                return(PlayerPrefs.HasKey(FileSystem.GetUnescapedAbsolutePath(uri)));
            }

            return(await UniTask.FromResult(File.Exists(FileSystem.GetUnescapedAbsolutePath(uri))));
        }
 /// <summary>
 ///     Executes the given action if the calling result is a success and condition is true. Returns the calling result.
 /// </summary>
 public static UniTask <Result <T> > TapIf <T>(this Result <T> result, Func <T, bool> predicate, Func <UniTask> func)
 {
     if (result.IsSuccess && predicate(result.Value))
     {
         return(result.Tap(func));
     }
     else
     {
         return(UniTask.FromResult(result));
     }
 }
        public UniTask Disconnect(Action action)
        {
#if UNITY_WEBGL
            foreach (var peri in this.peripherals)
            {
                WebBluetoothScript.Instance.Disconnect(peri.serverID);
            }
            this.peripherals.Clear();
#endif
            return(UniTask.FromResult <object>(null));
        }
Esempio n. 25
0
    async UniTaskVoid BarAsync()
    {
        var loop = int.Parse("10");


        var foo = await UniTask.FromResult(100);

        Debug.Log("OK");


        Debug.Log("Again");
    }
Esempio n. 26
0
        public async UniTask WhenAll()
        {
            var a = UniTask.FromResult(999);
            var b = UniTask.Yield().AsAsyncUnitUniTask();
            var c = UniTask.DelayFrame(99);

            var(a2, b2, c2) = await UniTask.WhenAll(a, b, c);

            a2.Is(999);
            b2.Is(AsyncUnit.Default);
            c2.Is(99);
        }
            public UniTask <BLEPeripheralInterface> Scan()
            {
                var cubeObjects = GameObject.FindGameObjectsWithTag("Cube");

                foreach (var obj in cubeObjects)
                {
                    if (!this.IDHash.Contains(obj.GetInstanceID()))
                    {
                        this.IDHash.Add(obj.GetInstanceID());
                        return(new UniTask <BLEPeripheralInterface>(new UnityPeripheral(obj) as BLEPeripheralInterface));
                    }
                }
                return(UniTask.FromResult <BLEPeripheralInterface>(null));
            }
        public UniTask <T[]> LoadAllAssetsAsync <T>(IProgress <float> progress = null, CancellationToken token = default) where T : Object
        {
            progress?.Report(1);
            string[] paths = AssetDatabase.GetAssetPathsFromAssetBundle(name);
            if (paths == null || paths.Length == 0)
            {
                return(UniTask.FromResult <T[]>(null));
            }

            return(UniTask.FromResult(paths
                                      .Select(AssetDatabase.LoadAssetAtPath <T>)
                                      .Where(x => x != null)
                                      .ToArray()));
        }
Esempio n. 29
0
        public async UniTask WhenAny()
        {
            var a = UniTask.FromResult(999);
            var b = UniTask.Yield().AsAsyncUnitUniTask();
            var c = UniTask.DelayFrame(99);

            var(win, a2, b2, c2) = await UniTask.WhenAny(a, b, c);

            win.Is(0);
            a2.hasResult.IsTrue();
            a2.result0.Is(999);
            b2.hasResult.IsFalse();
            c2.hasResult.IsFalse();
        }
Esempio n. 30
0
        public IEnumerator ObservableConversion() => UniTask.ToCoroutine(async() =>
        {
            var v = await Observable.Range(1, 10).ToUniTask();
            v.Is(10);

            v = await Observable.Range(1, 10).ToUniTask(useFirstValue: true);
            v.Is(1);

            v = await UniTask.DelayFrame(10).ToObservable().ToTask();
            v.Is(10);

            v = await UniTask.FromResult(99).ToObservable();
            v.Is(99);
        });