示例#1
0
        private IObservable<string> detect(string text)
        {
            var subject = new AsyncSubject<string>();
            string detectUri = String.Format(GetDetectUri(text), appId, HttpUtility.HtmlEncode(text));

            var wc = new WebClient();
            wc.OpenReadCompleted += new OpenReadCompletedEventHandler((obj, args) =>
            {
                if (args.Error != null)
                {
                    subject.OnError(args.Error);
                }
                else
                {
                    if (!args.Cancelled)
                    {
                        var xdoc = XDocument.Load(args.Result);
                        subject.OnNext(xdoc.Root.Value);
                    }
                    subject.OnCompleted();
                }
            });
            wc.OpenReadAsync(new Uri(detectUri));
            return subject;
        }
示例#2
0
        public void each_subscriber_is_scheduled_individually()
        {
            ManualScheduler scheduler = new ManualScheduler();

            AsyncSubject<int> subject = new AsyncSubject<int>(scheduler);

            StatsObserver<int> statsA = new StatsObserver<int>();
            StatsObserver<int> statsB = new StatsObserver<int>();

            subject.OnNext(1);
            subject.OnNext(2);
            subject.OnNext(3);
            subject.OnCompleted();

            subject.Subscribe(statsA);
            subject.Subscribe(statsB);

            scheduler.RunNext();

            Assert.IsTrue(statsA.NextCalled);
            Assert.IsFalse(statsB.NextCalled);

            scheduler.RunNext();

            Assert.IsTrue(statsB.NextCalled);
        }
示例#3
0
        public static IObservable<Unit> WriteAsync(this Stream This, byte[] data, int start, int length)
        {
            var ret = new AsyncSubject<Unit>();

            try
            {
                This.BeginWrite(data, start, length, result =>
                {
                    try
                    {
                        This.EndWrite(result);
                        ret.OnNext(Unit.Default);
                        ret.OnCompleted();
                    }
                    catch (Exception ex)
                    {
                        ret.OnError(ex);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                ret.OnError(ex);
            }

            return ret;
        }
        public void UploadPictureAsyncBasicTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var w = new AsyncSubject<FlickrResult<string>>();

            byte[] imageBytes = TestData.TestImageBytes;
            var s = new MemoryStream(imageBytes);
            s.Position = 0;

            string title = "Test Title";
            string desc = "Test Description\nSecond Line";
            string tags = "testtag1,testtag2";

            f.UploadPictureAsync(s, "Test.jpg", title, desc, tags, false, false, false, ContentType.Other, SafetyLevel.Safe, HiddenFromSearch.Visible,
                r => { w.OnNext(r); w.OnCompleted(); });

            var result = w.Next().First();

            if (result.HasError)
            {
                throw result.Error;
            }

            Assert.IsNotNull(result.Result);
            Console.WriteLine(result.Result);

            // Clean up photo
            f.PhotosDelete(result.Result);
        }
        public void PhotosetsGetContextAsyncTest()
        {
            Flickr f = TestData.GetInstance();

            var photosetId = "72157626420254033"; // Beamish
            var photos = f.PhotosetsGetPhotos(photosetId, 1, 100);
            var firstPhoto = photos.First();
            var lastPhoto = photos.Last();

            var w = new AsyncSubject<FlickrResult<Context>>();

            f.PhotosetsGetContextAsync(firstPhoto.PhotoId, photosetId, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);

            var context = result.Result;

            Assert.IsNull(context.PreviousPhoto, "As this is the first photo the previous photo should be null.");
            Assert.IsNotNull(context.NextPhoto, "As this is the first photo the next photo should not be null.");

            w = new AsyncSubject<FlickrResult<Context>>();

            f.PhotosetsGetContextAsync(lastPhoto.PhotoId, photosetId, r => { w.OnNext(r); w.OnCompleted(); });
            result = w.Next().First();

            Assert.IsFalse(result.HasError);

            context = result.Result;

            Assert.IsNull(context.NextPhoto, "As this is the last photo the next photo should be null.");
            Assert.IsNotNull(context.PreviousPhoto, "As this is the last photo the previous photo should not be null.");
        }
        public void PhotosetsGeneralAsyncTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var photoId1 = "7519320006"; // Tree/Write/Wall
            var photoId2 = "7176125763"; // Rainbow Rose

            var w = new AsyncSubject<FlickrResult<Photoset>>();
            f.PhotosetsCreateAsync("Test Photoset", photoId1, r => { w.OnNext(r); w.OnCompleted(); });

            var photosetResult = w.Next().First();
            Assert.IsFalse(photosetResult.HasError);
            var photoset = photosetResult.Result;

            try
            {
                var w2 = new AsyncSubject<FlickrResult<NoResponse>>();
                f.PhotosetsEditMetaAsync(photoset.PhotosetId, "New Title", "New Description", r => { w2.OnNext(r); w2.OnCompleted(); });
                var noResponseResult = w2.Next().First();
                Assert.IsFalse(noResponseResult.HasError);

                var w3 = new AsyncSubject<FlickrResult<NoResponse>>();
                f.PhotosetsAddPhotoAsync(photoset.PhotosetId, photoId2, r => { w3.OnNext(r); w3.OnCompleted(); });

                noResponseResult = w3.Next().First();
                Assert.IsFalse(noResponseResult.HasError);
            }
            finally
            {
                var w4 = new AsyncSubject<FlickrResult<NoResponse>>();
                // Clean up and delete photoset
                f.PhotosetsDeleteAsync(photoset.PhotosetId, r => { w4.OnNext(r); w4.OnCompleted(); });
                var noResponseResult = w4.Next().First();
            }
        }
        public void PhotosGetCountsAsyncTest()
        {
            DateTime date1 = DateTime.Today.AddMonths(-12);
            DateTime date2 = DateTime.Today.AddMonths(-6);
            DateTime date3 = DateTime.Today;

            DateTime[] uploadDates = new DateTime[] { date1, date2, date3 };

            Flickr f = TestData.GetAuthInstance();

            var w = new AsyncSubject<FlickrResult<PhotoCountCollection>>();
            f.PhotosGetCountsAsync(uploadDates, false, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);

            var counts = result.Result;

            Assert.AreEqual(2, counts.Count, "Should be two counts returned.");

            var count1 = counts[0];

            Assert.AreEqual(date1, count1.FromDate);
            Assert.AreEqual(date2, count1.ToDate);

            var count2 = counts[1];
            Assert.AreEqual(date2, count2.FromDate);
            Assert.AreEqual(date3, count2.ToDate);
        }
示例#8
0
文件: Program.cs 项目: niik/RxSpy
        static IEnumerable<Task> CreateConnectableObservables()
        {
            var subject = new AsyncSubject<Unit>();

            yield return Observable.Defer(() => Observable.Start(() => Unit.Default))
                .Multicast(subject)
                .RefCount()
                .ToTask();
        }
示例#9
0
 ///<summary>
 ///With AsyncSubject<T> ,the subscriber will only get all the last publication made.
 ///Simply, AsyncSubject has a one value buffer. The publication is made only on the OnCompleted() call.
 ///</summary>
 private static void AsyncSubject()
 {
     var subject = new AsyncSubject<string>();
         subject.OnNext("a");
         subject.OnNext("b");
         subject.OnNext("c");
         subject.Subscribe(Console.WriteLine);
         subject.OnCompleted();
 }
示例#10
0
文件: JobHost.cs 项目: Mecabot/RedDog
        public JobHost()
        {
            // Job container.
            Jobs = new Dictionary<string, Job>();

            // Signal 
            _shutdownSignal = new AsyncSubject<Unit>();
            _shutdownSignal.OnNext(Unit.Default);
        }
示例#11
0
 public static void Run()
 {
     var subject = new AsyncSubject<string>();
       subject.OnNext("a");
       WriteSequenceToConsole(subject);
       subject.OnNext("b");
       subject.OnNext("c");
       // subject.OnCompleted();
       Console.ReadLine();
 }
示例#12
0
        public void PhotosGetExifAsyncTest()
        {
            Flickr f = TestData.GetInstance();

            var w = new AsyncSubject<FlickrResult<ExifTagCollection>>();
            f.PhotosGetExifAsync(TestData.PhotoId, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);
        }
示例#13
0
        public void Infinite()
        {
            var scheduler = new TestScheduler();

            var xs = scheduler.CreateHotObservable(
                OnNext(70, 1),
                OnNext(110, 2),
                OnNext(220, 3),
                OnNext(270, 4),
                OnNext(340, 5),
                OnNext(410, 6),
                OnNext(520, 7),
                OnNext(630, 8),
                OnNext(710, 9),
                OnNext(870, 10),
                OnNext(940, 11),
                OnNext(1020, 12)
            );

            var subject = default(AsyncSubject<int>);
            var subscription = default(IDisposable);

            var results1 = scheduler.CreateObserver<int>();
            var subscription1 = default(IDisposable);

            var results2 = scheduler.CreateObserver<int>();
            var subscription2 = default(IDisposable);

            var results3 = scheduler.CreateObserver<int>();
            var subscription3 = default(IDisposable);

            scheduler.ScheduleAbsolute(100, () => subject = new AsyncSubject<int>());
            scheduler.ScheduleAbsolute(200, () => subscription = xs.Subscribe(subject));
            scheduler.ScheduleAbsolute(1000, () => subscription.Dispose());

            scheduler.ScheduleAbsolute(300, () => subscription1 = subject.Subscribe(results1));
            scheduler.ScheduleAbsolute(400, () => subscription2 = subject.Subscribe(results2));
            scheduler.ScheduleAbsolute(900, () => subscription3 = subject.Subscribe(results3));

            scheduler.ScheduleAbsolute(600, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(700, () => subscription2.Dispose());
            scheduler.ScheduleAbsolute(800, () => subscription1.Dispose());
            scheduler.ScheduleAbsolute(950, () => subscription3.Dispose());

            scheduler.Start();

            results1.Messages.AssertEqual(
            );

            results2.Messages.AssertEqual(
            );

            results3.Messages.AssertEqual(
            );
        }
        public void PhotosAddTagTest()
        {
            string photoId = "4499284951";
            string tag = "testx";

            var w = new AsyncSubject<FlickrResult<NoResponse>>();

            AuthInstance.PhotosAddTagsAsync(photoId, tag, r => { w.OnNext(r); w.OnCompleted(); });

            var result = w.Next().First();
        }
        public void PhotosGetContactsPhotosAsyncTest()
        {
            var w = new AsyncSubject<FlickrResult<PhotoCollection>>();
            AuthInstance.PhotosGetContactsPhotosAsync(50, true, true, true, PhotoSearchExtras.All, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);
            Assert.IsNotNull(result.Result);

            Assert.IsTrue(result.Result.Count > 0, "Should return some photos.");
        }
示例#16
0
        public void StatsGetPhotosetDomainsAsyncTest()
        {
            Flickr f = TestData.GetAuthInstance();

            DateTime d = DateTime.Today.AddDays(-7);

            var w = new AsyncSubject<FlickrResult<StatDomainCollection>>();
            f.StatsGetPhotosetDomainsAsync(d, 1, 25, r => { w.OnNext(r); w.OnCompleted(); });

            var result = w.Next().First();
            Assert.IsFalse(result.HasError);
        }
示例#17
0
        public void PhotosGetRecentAsyncTest()
        {
            Flickr f = TestData.GetInstance();
            var w = new AsyncSubject<FlickrResult<PhotoCollection>>();
            f.PhotosGetRecentAsync(1, 50, PhotoSearchExtras.All, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsFalse(result.HasError);
            Assert.IsNotNull(result.Result);

            Assert.IsTrue(result.Result.Count > 0, "Should return some photos.");
        }
        public void PhotosSearchAsyncBasicTest()
        {
            var o = new PhotoSearchOptions();
            o.Tags = "microsoft";

            var w = new AsyncSubject<FlickrResult<PhotoCollection>>();

            Instance.PhotosSearchAsync(o, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsTrue(result.Result.Total > 0);
        }
示例#19
0
        public JobHost(IJobEventContext eventContext)
        {
            // Job container.
            Jobs = new Dictionary<string, Job>();

            // Store the event context that will be used to track jobs and tasks.
            _eventContext = eventContext;

            // Signal 
            _shutdownSignal = new AsyncSubject<Unit>();
            _shutdownSignal.OnNext(Unit.Default);
        }
        public void Run()
        {
            ConsoleUtility.PrintSuccess(string.Format("Rx AsyncSubject example"));
            var topic = new AsyncSubject<Price>();
            WriteToConsole(topic);

            topic.OnNext(new Price(1, 99, 100, 101));
            topic.OnNext(new Price(1, 98, 99, 100));
            topic.OnNext(new Price(1, 97, 98, 99));

            topic.OnCompleted();
        }
示例#21
0
 public IObservable<Unit> Speak(string speechString)
 {
     var id = Interlocked.Increment(ref this.nextId);
     var result = new AsyncSubject<Unit>();
     inFlightSpeech.TryAdd(id, result);
     var parameters = new Dictionary<string, string>
     {
         [TextToSpeech.Engine.KeyParamUtteranceId] = id.ToString(),
         [TextToSpeech.Engine.KeyFeatureNetworkSynthesis] = "true"
     };
     this.textToSpeech.Speak(speechString, QueueMode.Add, parameters);
     return result;
 }
        private void Start()
        {
            //BehaviorSubjectは初期値を設定できる
            asyncSubject = new AsyncSubject<int>();

            /*
            Subscribe後にOnNextを繰り返しても値が発行されず、OnCompletedを実行した際に初めてOnNextが通知されるところ確認しよう
            また、その時のOnNextの値は最後の値1つだけになっていることも確認しよう
            */

            // Subscribeボタンが押されたらSubjectをSubscribeしてresultTextに表示する
            subscribeButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (asyncSubject != null)
                {
                    asyncSubject.Subscribe(
                        time => resultText.text += time.ToString() + " ", //OnNext
                        () => resultText.text += "OnCompleted "); //OnCompleted
                }
            });

            // OnNextボタンが押されたら今が何度目のOnNextであるかを発行する
            onNextButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (asyncSubject != null)
                {
                    asyncSubject.OnNext(++onNextCount);
                }
            });

            // OnCompletedボタンが押されたらOnCompletedを発行する
            onCompletedButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (asyncSubject != null)
                {
                    asyncSubject.OnCompleted();
                }
            });

            // Resetボタンが押されたら全体を初期化する
            resetButton.OnClickAsObservable().Subscribe(_ =>
            {
                if (asyncSubject != null)
                {
                    asyncSubject.OnCompleted();
                }
                asyncSubject = new AsyncSubject<int>();
                resultText.text = "";
                onNextCount = 0;
            });
        }
示例#23
0
        public void StatsGetCollectionStatsAsyncTest()
        {
            Flickr f = TestData.GetAuthInstance();

            var collection = f.CollectionsGetTree().First();

            DateTime d = DateTime.Today.AddDays(-7);

            var w = new AsyncSubject<FlickrResult<Stats>>();
            f.StatsGetCollectionStatsAsync(d, collection.CollectionId, r => { w.OnNext(r); w.OnCompleted(); });

            var result = w.Next().First();
            Assert.IsFalse(result.HasError);
        }
示例#24
0
        public void AuthGetFrobAsyncTest()
        {
            var w = new AsyncSubject<FlickrResult<string>>();

            TestData.GetOldSignedInstance().AuthGetFrobAsync(r => { w.OnNext(r); w.OnCompleted(); });

            var frobResult = w.Next().First();

            Assert.IsFalse(frobResult.HasError);

            string frob = frobResult.Result;

            Assert.IsNotNull(frob, "frob should not be null.");
            Assert.AreNotEqual("", frob, "Frob should not be zero length string.");
        }
示例#25
0
        public void StatsGetPhotoStatsAsyncTest()
        {
            Flickr.CacheDisabled = true;

            Flickr f = TestData.GetAuthInstance();

            DateTime d = DateTime.Today.AddDays(-7);

            var w = new AsyncSubject<FlickrResult<Stats>>();
            f.StatsGetPhotoStatsAsync(d, "7176125763", r => { w.OnNext(r); w.OnCompleted(); });

            var result = w.Next().First();
            if (result.HasError) throw result.Error;

            Assert.IsFalse(result.HasError);
        }
        public void PhotosAddTagTest()
        {
            Flickr f = TestData.GetAuthInstance();
            string photoId = "4499284951";
            string tag = "testx";

            var w = new AsyncSubject<FlickrResult<NoResponse>>();

            f.PhotosAddTagsAsync(photoId, tag, r => { w.OnNext(r); w.OnCompleted(); });

            //var result = w.Next().First();

            w.Next().First();

            //Assert.IsFalse(result.HasError);
        }
        public void PhotosSearchAsyncShowerTest()
        {
            var o = new PhotoSearchOptions();
            o.UserId = "78507951@N00";
            o.Tags = "shower";
            o.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
            o.PerPage = 1000;
            o.TagMode = TagMode.AllTags;
            o.Extras = PhotoSearchExtras.All;

            var w = new AsyncSubject<FlickrResult<PhotoCollection>>();

            AuthInstance.PhotosSearchAsync(o, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsTrue(result.Result.Total > 0);
        }
示例#28
0
        public Task Wait(string key)
        {
            lock (this.keyedSemaphore)
            {
                AsyncSubject<Unit> semaphore;

                if (this.keyedSemaphore.TryGetValue(key, out semaphore))
                {
                    return semaphore.ToTask();
                }

                semaphore = new AsyncSubject<Unit>();
                this.keyedSemaphore.Add(key, semaphore);

                return Task.Delay(0);
            }
        }
示例#29
0
 public IObservable<TwitterSearchStatus> Search(string query, int page, int rpp)
 {
     var subject = new AsyncSubject<IEnumerable<TwitterSearchStatus>>();
     this.service.Search(query, page, rpp, (tr, res) =>
     {
         if (res.InnerException == null)
         {
             subject.OnNext(tr.Statuses);
             subject.OnCompleted();
         }
         else
         {
             subject.OnError(res.InnerException);
         }
     });
     return subject.AsObservable().SelectMany(r => r);
 }
        public static IObservable <T> ToObservable <T>(this UniTask <T> task)
        {
            if (task.Status.IsCompleted())
            {
                try
                {
                    return(new ReturnObservable <T>(task.GetAwaiter().GetResult()));
                }
                catch (Exception ex)
                {
                    return(new ThrowObservable <T>(ex));
                }
            }

            var subject = new AsyncSubject <T>();

            Fire(subject, task).Forget();
            return(subject);
        }
示例#31
0
        private static OperationQueueItem GroupUnrelatedDeletes(IEnumerable <OperationQueueItem> unrelatedDeletes)
        {
            var subj = new AsyncSubject <Unit>();
            var operationQueueItems = unrelatedDeletes.ToList();

            if (operationQueueItems.Count == 1)
            {
                return(operationQueueItems[0]);
            }

            var elements = operationQueueItems.SelectMany(x =>
            {
                subj.Subscribe(x.CompletionAsUnit);
                return(x.ParametersAsKeys);
            }).ToList();

            return(OperationQueueItem.CreateInvalidate(
                       OperationType.BulkInvalidateSqliteOperation, elements, subj));
        }
示例#32
0
        public static void AsyncSubject_OnlyPubWhenCompleted()
        {
            var recorder = new RecordObserver();

            ISubject <int> subject = new AsyncSubject <int>();

            subject.Subscribe(recorder);

            subject.OnNext(1);
            subject.OnNext(2);
            Assert.IsFalse(recorder.LastValue.HasValue);
            Assert.AreEqual(0, recorder.NumOfNextInvoke);

            subject.OnCompleted();
            Assert.IsTrue(recorder.LastValue.HasValue);
            Assert.AreEqual(2, recorder.LastValue);
            Assert.IsTrue(recorder.IsCompleted);
            Assert.AreEqual(1, recorder.NumOfNextInvoke);
        }
示例#33
0
        public virtual AsyncSubject <TSource> RunAsync <TSource>(IConnectableObservable <TSource> source, CancellationToken cancellationToken)
        {
            var s = new AsyncSubject <TSource>();

            if (cancellationToken.IsCancellationRequested)
            {
                return(Cancel(s, cancellationToken));
            }

            var d = source.SubscribeSafe(s);
            var c = source.Connect();

            if (cancellationToken.CanBeCanceled)
            {
                RegisterCancelation(s, StableCompositeDisposable.Create(d, c), cancellationToken);
            }

            return(s);
        }
示例#34
0
        public SocketServer(IExecutor executor, IPEndPoint bindEndPoint)
        {
            Ensure.IsNotNull(executor, "executor");
            Ensure.IsNotNull(bindEndPoint, "bindEndPoint");

            this.executor = executor;

            this.started   = new AsyncSubject <Unit>();
            this.stopped   = new AsyncSubject <Unit>();
            this.connected = new Subject <SocketClient>();

            if (bindEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
            {
                if (!Socket.OSSupportsIPv6)
                {
                    throw new InvalidOperationException("OS does not support IPv6");
                }

                this.socket = new Socket(AddressFamily.InterNetworkV6,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);
#if !MONO
                if (IsWinVistaOrHigher() || IsNotWindows())
                {
                    try
                    {
                        this.socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
                    }
                    catch { }
                }
#endif
            }
            else
            {
                this.socket = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);
            }
            this.acceptArgs   = new SocketAsyncEventArgs();
            this.bindEndPoint = bindEndPoint;

            this.acceptArgs.Completed += SocketAccepted;
        }
示例#35
0
        public ActorClientProxyTemplate(IPEndPoint endPoint)
        {
            this.endPoint     = endPoint;
            this.disconnected = false;

            this.disconnectedSubject = new AsyncSubject <Exception>();
            serializer             = new ProtoBufStacksSerializer();
            replyHandlersByRequest = new Dictionary <long, Action <MemoryStream, Exception> >();
            obsHandlers            = new Dictionary <string, Action <MemoryStream> >();
            exec        = new ActionBlockExecutor();
            exec.Error += ExecutionError;
            client      = new ActorRemoteMessageClient(
                new FramedClient(
                    new SocketClient(exec)));

            client.MessageReceived    += MessageReceived;
            client.ObsMessageReceived += ObsMessageReceived;
            client.Disconnected.Subscribe(HandleDisconnection);
        }
示例#36
0
        public SocketServer(IExecutor executor, IPEndPoint bindEndPoint)
        {
            Ensure.IsNotNull(executor, "executor");
            Ensure.IsNotNull(bindEndPoint, "bindEndPoint");

            this.executor = executor;

            this.started = new AsyncSubject<Unit>();
            this.stopped = new AsyncSubject<Unit>();
            this.connected = new Subject<SocketClient>();

            if (bindEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
            {
                if (!Socket.OSSupportsIPv6)
                {
                    throw new InvalidOperationException("OS does not support IPv6");
                }

                this.socket = new Socket(AddressFamily.InterNetworkV6,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);
            #if !MONO
                if (IsWinVistaOrHigher() || IsNotWindows())
                {
                    try
                    {
                        this.socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
                    }
                    catch { }
                }
            #endif
            }
            else
            {
                this.socket = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);
            }
            this.acceptArgs = new SocketAsyncEventArgs();
            this.bindEndPoint = bindEndPoint;

            this.acceptArgs.Completed += SocketAccepted;
        }
示例#37
0
        public AsyncInfoToObservableBridge(IAsyncInfo info, Action <IAsyncInfo, Action <IAsyncInfo, AsyncStatus> > onCompleted, Func <IAsyncInfo, TResult> getResult, Action <IAsyncInfo, Action <IAsyncInfo, TProgress> > onProgress, IProgress <TProgress> progress, bool multiValue)
        {
            _onCompleted = onCompleted;
            _getResult   = getResult;

            _subject = new AsyncSubject <TResult>();

            onProgress?.Invoke(info, (iai, p) =>
            {
                if (multiValue && getResult != null)
                {
                    _subject.OnNext(getResult(iai));
                }

                progress?.Report(p);
            });

            Done(info, info.Status, true);
        }
        public virtual AsyncSubject <TSource> RunAsync <TSource>(IConnectableObservable <TSource> source, CancellationToken cancellationToken)
        {
            var s = new AsyncSubject <TSource>();

            var cancel = new Action(() => s.OnError(new OperationCanceledException()));

            if (cancellationToken.IsCancellationRequested)
            {
                cancel();
                return(s);
            }

            var d = new CompositeDisposable(source.SubscribeSafe(s), source.Connect());

            cancellationToken.Register(d.Dispose);
            cancellationToken.Register(cancel);

            return(s);
        }
示例#39
0
        /// <summary>
        /// Ideally returns IObservabl[Unit] is best but UniRx.Async does not have Unit so return AsyncUnit instead.
        /// </summary>
        public static IObservable <AsyncUnit> ToObservable(this UniTask task)
        {
            if (task.IsCompleted)
            {
                try
                {
                    return(new ReturnObservable <AsyncUnit>(AsyncUnit.Default));
                }
                catch (Exception ex)
                {
                    return(new ThrowObservable <AsyncUnit>(ex));
                }
            }

            var subject = new AsyncSubject <AsyncUnit>();

            Fire(subject, task).Forget();
            return(subject);
        }
示例#40
0
        public static IObservable <RestResponse <T> > RequestAsync <T>(this RestClient This, RestRequest request)
        {
            var ret = new AsyncSubject <RestResponse <T> >();

            This.BeginRequest <T>(request, (rq, resp, state) =>
            {
                try
                {
                    ret.OnNext(resp);
                    ret.OnCompleted();
                }
                catch (Exception ex)
                {
                    ret.OnError(ex);
                }
            });

            return(ret);
        }
示例#41
0
        /// <summary>
        /// Allows explicitly requesting channel to connect without starting an RPC.
        /// Returned task completes once state Ready was seen. If the deadline is reached,
        /// or channel enters the Shutdown state, the task is cancelled.
        /// There is no need to call this explicitly unless your use case requires that.
        /// Starting an RPC on a new channel will request connection implicitly.
        /// </summary>
        /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
        public IObservable <Unit> ConnectAsync(DateTime?deadline = null)
        {
            var currentState = GetConnectivityState(true);

            if (currentState == ChannelState.Ready)
            {
                return(Observable.ReturnUnit());
            }

            if (currentState == ChannelState.Shutdown)
            {
                return(Observable.Throw <Unit>(new OperationCanceledException("Channel has reached Shutdown state.")));
            }

            var subject = new AsyncSubject <Unit>();

            TryWaitForStateChangedAsync(subject, currentState, deadline);
            return(subject);
        }
示例#42
0
        /// <summary>
        /// The ask to observable.
        /// </summary>
        /// <param name="question">
        /// The question.
        /// </param>
        /// <param name="buttons">
        /// The buttons.
        /// </param>
        /// <returns>
        /// The <see cref="IObservable"/>.
        /// </returns>
        public IObservable <MessageBoxResult> AskToObservable(string question, MessageBoxButton buttons)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(question));

            var subject = new AsyncSubject <MessageBoxResult>();

            var newQuestions = new Question
            {
                Body     = question,
                Buttons  = buttons,
                Callback = result => {
                    subject.OnNext(result);
                    subject.OnCompleted();
                }
            };

            this.Add(newQuestions);
            return(subject);
        }
示例#43
0
        public async Task Should_Send_and_receive_notifications()
        {
            var clientNotification = new AsyncSubject <Data>();
            var serverNotification = new AsyncSubject <Data>();

            var(client, server) = await Initialize(
                clientOptions =>
            {
                clientOptions.OnNotification(
                    "mynotification", (Data data) =>
                {
                    clientNotification.OnNext(data);
                    clientNotification.OnCompleted();
                }
                    );
            },
                serverOptions =>
            {
                serverOptions.OnNotification(
                    "mynotification", (Data data) =>
                {
                    serverNotification.OnNext(data);
                    serverNotification.OnCompleted();
                }
                    );
            }
                );

            client.SendNotification("mynotification", new Data {
                Value = "myresponse"
            });
            var serverResponse = await serverNotification;

            serverResponse.Value.Should().Be("myresponse");

            server.SendNotification("mynotification", new Data {
                Value = string.Join("", "myresponse".Reverse())
            });
            var clientResponse = await clientNotification;

            clientResponse.Value.Should().Be("esnopserym");
        }
示例#44
0
        /// <summary>
        /// Adding new source stream to run
        /// </summary>
        /// <param name="Source">any observable streams</param>
        public void Add <T>(UniRx.IObservable <T> Source)
        {
            lock (_gate)
            {
                if (_tail != null)
                {
                    var newHead = new AsyncSubject <Unit>();

                    _tail
                    .Subscribe(_ =>
                    {
                        var streamToLink =
                            Source
                            .DoOnCompleted(() =>
                        {
                            newHead.OnNext(Unit.Default);
                            newHead.OnCompleted();
                        }).Subscribe();

                        _queHistory.Add(streamToLink);
                    });
                    _tail = newHead;
                    _queHistory.Add(_tail);
                }
                else
                {
                    var head = new AsyncSubject <Unit>();

                    var initialStream =
                        Source
                        .DoOnCompleted(() =>
                    {
                        head.OnNext(Unit.Default);
                        head.OnCompleted();
                    }).Subscribe();

                    _queHistory.Add(initialStream);
                    _tail = head;
                    _queHistory.Add(_tail);
                }
            }
        }
示例#45
0
        public void CancellingItemsShouldNotResultInThemBeingReturned()
        {
            var subj1 = new AsyncSubject <int>();
            var subj2 = new AsyncSubject <int>();

            var fixture = new OperationQueue(2);

            // Block up the queue
            foreach (var v in new[] { subj1, subj2, })
            {
                fixture.EnqueueObservableOperation(5, () => v);
            }

            var cancel1 = new Subject <Unit>();
            var item1   = new AsyncSubject <int>();
            var output  = new[] {
                fixture.EnqueueObservableOperation(5, "foo", cancel1, () => item1),
                fixture.EnqueueObservableOperation(5, "baz", () => Observable.Return(42)),
            }.Merge().CreateCollection();

            // Still blocked by subj1,2
            Assert.Equal(0, output.Count);

            // Still blocked by subj1,2, only baz is in queue
            cancel1.OnNext(Unit.Default); cancel1.OnCompleted();
            Assert.Equal(0, output.Count);

            // foo was cancelled, baz is still good
            subj1.OnNext(42);
            subj1.OnCompleted();
            Assert.Equal(1, output.Count);

            // don't care that cancelled item finished
            item1.OnNext(42);
            item1.OnCompleted();
            Assert.Equal(1, output.Count);

            // still shouldn't see anything
            subj2.OnNext(42);
            subj2.OnCompleted();
            Assert.Equal(1, output.Count);
        }
示例#46
0
        public void CancellingItemsShouldntEvenBeEvaluated()
        {
            var subj1 = new AsyncSubject <int>();
            var subj2 = new AsyncSubject <int>();

            var fixture = new OperationQueue(2);

            // Block up the queue
            foreach (var v in new[] { subj1, subj2, })
            {
                fixture.EnqueueObservableOperation(5, () => v);
            }

            var  cancel1   = new Subject <Unit>();
            bool wasCalled = false;
            var  item1     = new AsyncSubject <int>();

            var output = fixture.EnqueueObservableOperation(5, "foo", cancel1, () => {
                wasCalled = true;
                return(item1);
            }).CreateCollection();

            // Still blocked by subj1,2
            Assert.Equal(0, output.Count);
            Assert.False(wasCalled);

            // Still blocked by subj1,2 - however, we've cancelled foo before
            // it even had a chance to run - if that's the case, we shouldn't
            // even call the evaluation func
            cancel1.OnNext(Unit.Default); cancel1.OnCompleted();
            Assert.Equal(0, output.Count);
            Assert.False(wasCalled);

            // Unblock subj1,2, we still shouldn't see wasCalled = true
            subj1.OnNext(42); subj1.OnCompleted();
            Assert.Equal(0, output.Count);
            Assert.False(wasCalled);

            subj2.OnNext(42); subj2.OnCompleted();
            Assert.Equal(0, output.Count);
            Assert.False(wasCalled);
        }
示例#47
0
        /// <summary>
        /// Acquires the read or write lock on the scheduler, as observable.
        /// </summary>
        /// <param name="schedulingTaskFactory">The task factory.</param>
        /// <returns></returns>
        private IObservable <ReaderWriterLock> AcquireReadOrWriteLockObservable(TaskFactory schedulingTaskFactory)
        {
            // check for incorrect entry once we have already been disposed
            if (IsDisposed)
            {
                return(Observable.Throw <ReaderWriterLock>(new ObjectDisposedException(this.GetType().Name)));
            }

            // basically what happens here is we use the (concurrent) reader or (exclusive) handed in
            // and schedule a new tpl task on it which merely wraps or contains chained IDisposable creation.
            // What happens then is, we return a 'future' promise or timeslot for whenever the ConcurrentExclusiveSchedulerPair
            // does actually start working on that TPL task (meaning that by its own, internal r/w locking, the task was up next).

            // this is the result we hand back to the caller
            var asyncSubject = new AsyncSubject <ReaderWriterLock>();
            var gate         = new AsyncSubject <Unit>();

            schedulingTaskFactory.StartNew(async() =>
            {
                // this asyncSubject is the one actually handed back to the method's caller as IDisposable instance
                // & whenever that one is disposed, the gate gets unblocked \o/
                asyncSubject.OnNext(
                    new ReaderWriterLock(
                        Interlocked.Increment(ref _scheduledOperationId),
                        schedulingTaskFactory == ExclusiveTaskFactory,
                        Disposable.Create(() =>
                {
                    gate.OnNext(Unit.Default);
                    gate.OnCompleted();
                })));
                asyncSubject.OnCompleted();

                // once the asyncSubject's ticket has been disposed, this gate gets unlocked, too
                await gate;

                // cleanup
                gate.Dispose();
                gate = null;
            });

            return(asyncSubject);
        }
示例#48
0
        AsyncSubject <byte[]> FetchOrWriteBlobFromDisk(string key, object byteData, bool synchronous)
        {
            // If this is secretly a write, dispatch to WriteBlobToDisk (we're
            // kind of abusing the 'context' variable from MemoizingMRUCache
            // here a bit)
            if (byteData != null)
            {
                return(WriteBlobToDisk(key, (byte[])byteData, synchronous));
            }

            var ret = new AsyncSubject <byte[]>();
            var ms  = new MemoryStream();

            var scheduler = synchronous ? System.Reactive.Concurrency.Scheduler.Immediate : Scheduler;

            if (disposed)
            {
                Observable.Throw <byte[]>(new ObjectDisposedException("PersistentBlobCache"))
                .Multicast(ret)
                .PermaRef();
                return(ret);
            }

            Func <IObservable <byte[]> > readResult = () =>
                                                      Observable.Defer(() =>
                                                                       filesystem.SafeOpenFileAsync(GetPathForKey(key), FileMode.Open, FileAccess.Read, FileShare.Read, scheduler))
                                                      .Retry(1)
                                                      .SelectMany(x => x.CopyToAsync(ms, scheduler))
                                                      .SelectMany(x => AfterReadFromDiskFilter(ms.ToArray(), scheduler))
                                                      .Catch <byte[], FileNotFoundException>(ex => ObservableThrowKeyNotFoundException(key, ex))
                                                      .Catch <byte[], IsolatedStorageException>(ex => ObservableThrowKeyNotFoundException(key, ex))
                                                      .Do(_ =>
            {
                if (!synchronous && key != BlobCacheIndexKey)
                {
                    actionTaken.OnNext(Unit.Default);
                }
            });

            readResult().Multicast(ret).PermaRef();
            return(ret);
        }
示例#49
0
        public virtual IObservable <bool> ConnectAsync(string serverAddress, string applicationName)
        {
            ValidateDisposed();

            var future             = new AsyncSubject <bool>();
            var watchStatusChanged = new SingleAssignmentDisposable();

            watchStatusChanged.Disposable = this.ObserveStatusChanged().Subscribe(x =>
            {
                if (x == StatusCode.ExceptionOnConnect)
                {
                    watchStatusChanged.Dispose();
                    future.OnError(new ConnectionFailedException(serverAddress, applicationName));
                }

                if (x == StatusCode.Connect)
                {
                    watchStatusChanged.Dispose();

                    future.OnNext(true);
                    future.OnCompleted();
                }
            });

            if (this.Connect(serverAddress, applicationName))
            {
                this.LastConnectServerAddress   = serverAddress;
                this.LastConnectApplicationName = applicationName;

                return(future.Timeout(Timeout).Catch((Exception ex) =>
                {
                    watchStatusChanged.Dispose();
                    this.Disconnect();
                    return Observable.Throw <bool>(ex);
                }));
            }
            else
            {
                watchStatusChanged.Dispose();
                return(Observable.Return(false));
            }
        }
示例#50
0
        /// <summary>
        /// Starts a streamed request - unary response call.
        /// Use StartSendMessage and StartSendCloseFromClient to stream requests.
        /// </summary>
        public IObservable <TResponse> ClientStreamingCallAsync()
        {
            lock (myLock)
            {
                GrpcPreconditions.CheckState(!started);
                started = true;

                Initialize(details.Channel.CompletionQueue);

                readingDone = true;

                unaryResponseTcs = new AsyncSubject <TResponse>();
                using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
                {
                    call.StartClientStreaming(HandleUnaryResponse, metadataArray);
                }

                return(unaryResponseTcs);
            }
        }
示例#51
0
        public IObservable <Unit> Flush()
        {
            var ret = new AsyncSubject <Unit>();

            return(Task.Run(async() =>
            {
                // NB: We add a "DoNothing" operation so that the thread waiting
                // on an item will always have one instead of waiting the full timeout
                // before we can run the flush
                operationQueue.Add(OperationQueueItem.CreateUnit(OperationType.DoNothing));

                using (await flushLock.LockAsync())
                {
                    var newQueue = new BlockingCollection <OperationQueueItem>();
                    var existingItems = Interlocked.Exchange(ref operationQueue, newQueue).ToList();

                    ProcessItems(CoalesceOperations(existingItems));
                }
            }).ToObservable());
        }
示例#52
0
        public AsyncSubject <Unit> AddCards(List <TimelineSerializableData> items)
        {
            AsyncSubject <Unit> subject   = new AsyncSubject <Unit>();
            Func <UniTask>      asyncFunc = async() =>
            {
                var doTweenList = new DOTweenList();
                items.ForEach(item =>
                {
                    var turnCard = CreateCard(item);
                    doTweenList.Add(AddCardAnimation(turnCard.transform, _turnCards.Count));
                });
                await doTweenList;
                ActiveCardGrow();
                subject.OnNext(Unit.Default);
                subject.OnCompleted();
            };

            asyncFunc();
            return(subject);
        }
示例#53
0
        static void MainAS(string[] args)
        {
            Task <int> t = Task <int> .Factory.StartNew(() => 42);

            int value = t.Result;

            // AsyncSubject always stores the last value, and only
            // gives it up on OnCompleted

            AsyncSubject <double> sensor = new AsyncSubject <double>();

            sensor.OnNext(10);
            sensor.Subscribe(Console.WriteLine);
            sensor.OnNext(20);
            sensor.OnCompleted();

            // implicit contact - sequence ends in either
            // OnCompleted or OnError
            sensor.OnNext(30); // does nothing
        }
示例#54
0
        /* Getting from A to B:
         *
         * This is what it might look like if we wrapped this method by-hand. Writing
         * this code over and over again would get really boring, but it's good to do it
         * once to see what it would look like.
         */
        public static IObservable <string> DownloadPageTextRx(string url)
        {
            var subject = new AsyncSubject <string>();

            // Call our original method
            try
            {
                DownloadPageTextAsync(url, (pageText) =>
                {
                    subject.OnNext(pageText);
                    subject.OnCompleted();
                });
            }
            catch (Exception ex)
            {
                subject.OnError(ex);
            }

            return(subject);
        }
示例#55
0
        public static IObservable <Unit> ToObservable(this Task This)
        {
            var ret = new AsyncSubject <Unit>();

            This.ContinueWith(x => {
                try {
                    if (x.Exception != null)
                    {
                        ret.OnError(x.Exception);
                        return;
                    }
                    ret.OnNext(Unit.Default);
                    ret.OnCompleted();
                } catch (Exception ex) {
                    ret.OnError(ex);
                }
            });

            return(ret);
        }
示例#56
0
        /// <summary>
        /// Invalidates all objects of the specified type. To invalidate all
        /// objects regardless of type, use InvalidateAll.
        /// </summary>
        /// <remarks>Returns a Unit for each invalidation completion. Use Wait instead of First to wait for
        /// this.</remarks>
        public static IObservable <Unit> InvalidateAllObjects <T>(this IBlobCache This)
        {
            var objCache = This as IObjectBlobCache;

            if (objCache != null)
            {
                return(objCache.InvalidateAllObjects <T>());
            }
            var ret = new AsyncSubject <Unit>();

            This.GetAllKeys().Where(x => x.StartsWith(GetTypePrefixedKey("", typeof(T))))
            .ToObservable()
            .SelectMany(This.Invalidate)
            .Subscribe(
                _ => { },
                ex => ret.OnError(ex),
                () => { ret.OnNext(Unit.Default); ret.OnCompleted(); });

            return(ret);
        }
        public void PhotosSearchAsyncShowerTest()
        {
            Flickr f = TestData.GetAuthInstance();

            PhotoSearchOptions o = new PhotoSearchOptions();

            o.UserId    = "78507951@N00";
            o.Tags      = "shower";
            o.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
            o.PerPage   = 1000;
            o.TagMode   = TagMode.AllTags;
            o.Extras    = PhotoSearchExtras.All;

            var w = new AsyncSubject <FlickrResult <PhotoCollection> >();

            f.PhotosSearchAsync(o, r => { w.OnNext(r); w.OnCompleted(); });
            var result = w.Next().First();

            Assert.IsTrue(result.Result.Total > 0);
        }
        /// <summary>
        /// Returns an observable sequence that signals when the task completes.
        /// </summary>
        /// <param name="task">Task to convert to an observable sequence.</param>
        /// <returns>An observable sequence that produces a unit value when the task completes, or propagates the exception produced by the task.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="task"/> is null.</exception>
        /// <remarks>If the specified task object supports cancellation, consider using <see cref="Observable.FromAsync(Func{CancellationToken, Task})"/> instead.</remarks>
        public static IObservable <Unit> ToObservable(this Task task)
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            // AsyncSubject<Unit>: Represents the result of an asynchronous operation.
            var subject = new AsyncSubject <Unit>();

            if (task.IsCompleted)
            {
                ToObservableDone(task, subject);
            }
            else
            {
                ToObservableSlow(task, subject);
            }

            return(subject.AsObservable());
        }
示例#59
0
        public async Task OneObserverTwoItems()
        {
            var    subject = new AsyncSubject <int>();
            string result  = "";

            var t = subject
                    .Finally(() => result       += "F")
                    .SubscribeAsync(i => result += i, ex => result += "E", () => result += "C");

            await subject.OnNextAsync(1);

            await subject.OnNextAsync(2);

            await subject.DisposeAsync();

            await t;

            result
            .Should().Be("12FC");
        }
示例#60
0
        public void HasObservers_Dispose2()
        {
            var s = new AsyncSubject <int>();

            Assert.IsFalse(s.HasObservers);
            Assert.IsFalse(s.IsDisposed);

            var d = s.Subscribe(_ => { });

            Assert.IsTrue(s.HasObservers);
            Assert.IsFalse(s.IsDisposed);

            d.Dispose();
            Assert.IsFalse(s.HasObservers);
            Assert.IsFalse(s.IsDisposed);

            s.Dispose();
            Assert.IsFalse(s.HasObservers);
            Assert.IsTrue(s.IsDisposed);
        }