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; }); }
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); }
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 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); }
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; }
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 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."); }
///<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(); }
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); }
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."); }
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 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 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(); }
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); }
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); }
/// <summary> /// WebContextのログインを行う。 /// </summary> /// <param name="self"></param> /// <param name="userName">ユーザ名</param> /// <param name="password">パスワード</param> /// <returns>ユーザ情報。ログインできていない場合はnull。</returns> public static IObservable<User> LoginAsObservable(this WebContext self, string userName, string password) { // Subscribeまで処理を遅延させるためDeferでくるむ return Observable.Defer(() => { var async = new AsyncSubject<User>(); // ログインを行う var op = self.Authentication.Login(userName, password); // Completedイベントを購読して Observable.FromEvent<EventHandler, EventArgs>( h => (s, e) => h(e), h => op.Completed += h, h => op.Completed -= h) // 1回のイベント発火でイベントハンドラを解除する .Take(1) .Subscribe(_ => { // キャンセルされてたら何もせず終了 if (op.IsCanceled) { async.OnCompleted(); return; } // エラーの場合はエラー通知 if (op.HasError) { op.MarkErrorAsHandled(); async.OnError(op.Error); return; } // ユーザ情報を発行して終了。 async.OnNext(op.User as User); async.OnCompleted(); }); return async.AsObservable(); }); }
public void AsyncSubjectPush() { var subj = new AsyncSubject <int>(); subj.Subscribe(v => Volatile.Write(ref _store, v)); var n = N; for (var i = 0; i < N; i++) { subj.OnNext(i); } subj.OnCompleted(); }
public void StatsGetPhotosetDomainsAsyncTest() { Flickr f = AuthInstance; 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); }
public AsyncSubject <Unit> SleepEffect(int uniqId) { AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); var sleep = Instantiate((GameObject)Resources.Load("Prefabs/Status/Sleep")); var skillBehavior = sleep.GetComponent <SkillBehavior>(); skillBehavior.EffectPlay(uniqId); ObservableUtils.Timer(200).Subscribe(_ => { subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
public void StatsGetPhotostreamStatsAsyncTest() { Flickr f = TestData.GetAuthInstance(); DateTime d = DateTime.Today.AddDays(-7); var w = new AsyncSubject<FlickrResult<Stats>>(); f.StatsGetPhotostreamStatsAsync(d, r => { w.OnNext(r); w.OnCompleted(); }); var result = w.Next().First(); Assert.IsFalse(result.HasError); Assert.IsTrue(result.Result.Views > 0, "Views should be greater than 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); }
/// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse")) { AsyncSubject <Unit> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessage, out msg); lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } responseHeadersTcs.OnNext(responseHeaders); responseHeadersTcs.OnCompleted(); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.OnError(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.OnError(new RpcException(status, () => (finishedStatus.HasValue) ? GetTrailers() : null)); return; } unaryResponseTcs.OnNext(msg); unaryResponseTcs.OnCompleted(); } }
public static AsyncSubject <Unit> StatusEffect(List <StatusUpdateResult> results, int uniqId, int activeUniqId) { AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); int count = 0; var subjects = new SubjectContainer(); var fromBattler = BattlerDictionary.GetBattlerByUniqId(uniqId); results.ForEach(x => { switch (x.StatusType) { case StatusConsts.POISON: AnnounceTextView.Instance.PoisonText(fromBattler, x.Value, x.IsDead); List <SkillDamage> damage = new List <SkillDamage>(); damage.Add(new SkillDamage() { damage = x.Value, valueTarget = SkillConsts.HP }); List <SkillDamages> damageses = new List <SkillDamages>(); damageses.Add(new SkillDamages() { isHit = true, SkillDamage = damage, targetUniqId = uniqId, isDead = x.IsDead }); subjects.Add(EffectManager.Instance.PoisonEffect(uniqId, damageses)); break; case StatusConsts.SLEEP: if (uniqId == activeUniqId) { AnnounceTextView.Instance.SleepText(fromBattler); subjects.Add(EffectManager.Instance.SleepEffect(uniqId)); } break; } }); subjects.Play().Subscribe(_ => { subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
public IObservable <IParseResult <TResult> > Parse(IObservableCursor <TSource> source) { return(Observable.Defer(() => { var completed = new AsyncSubject <Unit>(); bool hasResult = false; return parsers.Select( parser => Observable.Create <IParseResult <TResult> >( observer => { return parser.Parse(source).SubscribeSafe( result => { if (!hasResult) { hasResult = true; /* The XML lab has shown that Parse may be called multiple times on the same AnyObservableParser * instance during a single Parse operation, sometimes with the same source but most of the time * with a different source; therefore, the selected parser must be reassigned to the latest selection * for each call to Parse, maintaining a local variable (hasResult) to determine whether the current * call to Parse has matched while enumerating the choices. * * It is currently unknown whether it is possible for a nested Parse operation to overwrite the * selected parser, or whether it will have any negative impact. */ selectedParser = parser; } observer.OnNext(result); }, observer.OnError, () => { if (hasResult) { completed.OnNext(new Unit()); completed.OnCompleted(); } observer.OnCompleted(); }); })) .Concat() .TakeUntil(completed); })); }
internal static IObservable <T> ToAsyncSource <T>(this IObservable <T> source, Duration lifetime, IClock clock) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var gate = new object(); AsyncSubject <T>?subject = null; IDisposable? connection = null; var updated = Instant.MinValue; var complete = false; return(Observable.Create <T>(observer => { lock (gate) { if (subject == null || ((clock.GetCurrentInstant() - updated > lifetime || !complete) && !subject.HasObservers)) { subject?.Dispose(); subject = new AsyncSubject <T>(); complete = false; updated = clock.GetCurrentInstant(); connection?.Dispose(); connection = source .Subscribe( onNext: subject.OnNext, onError: subject.OnError, onCompleted: () => { lock (gate) { complete = true; subject.OnCompleted(); } }); } var subscription = subject.Subscribe(observer); return Disposable.Create(() => { lock (gate) subscription.Dispose(); }); } })); }
public void PhotosSearchAsyncBasicTest() { Flickr f = TestData.GetInstance(); PhotoSearchOptions o = new PhotoSearchOptions(); o.Tags = "microsoft"; 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); }
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."); }
private void HandleDisconnection(Exception exn) { foreach (var handler in replyHandlersByRequest) { var h = handler.Value; h(null, exn); } replyHandlersByRequest.Clear(); disconnected = true; disconnectedException = exn; disconnectedSubject.OnNext(exn); disconnectedSubject.OnCompleted(); }
static async UniTaskVoid Fire(AsyncSubject <AsyncUnit> subject, UniTask task) { try { await task; } catch (Exception ex) { subject.OnError(ex); return; } subject.OnNext(AsyncUnit.Default); subject.OnCompleted(); }
public static void TestOnlyPubLastWhenCompleted() { ISubject <int> stream = new AsyncSubject <int>(); stream.AttachConsoleHandlers(); foreach (int num in Enumerable.Range(1, 3)) { Console.WriteLine("\tdata generated: {0}", num); stream.OnNext(num); } Helper.Pause(); stream.OnCompleted(); }
public static void TheLastValueBeforeCompletion() { var subject = new AsyncSubject <int>(); var consoleObserver = new ConsoleObserver <int>(); var subscription = subject.Subscribe(consoleObserver); var observer2 = new ConsoleObserver <int>(); var subscription2 = subject.Subscribe(observer2); subject.OnNext(9); subject.OnCompleted(); subscription.Dispose(); subscription2.Dispose(); }
/// <summary> /// Returned tasks completes once channel state has become different from /// given lastObservedState. /// If deadline is reached or and error occurs, returned task is cancelled. /// </summary> public IObservable <bool> WaitForStateChangedAsync(ChannelState lastObservedState, DateTime?deadline = null) { GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown, "Shutdown is a terminal state. No further state changes can occur."); var subject = new AsyncSubject <bool>(); var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture; var handler = new BatchCompletionDelegate((success, ctx) => { subject.OnNext(success); subject.OnCompleted(); }); handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, handler); return(subject); }
public static void Async_Subject() { // 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 }
void Dispose(bool disposing) { if (disposing) { if (disposed) { return; } Scheduler = null; shutdown.OnNext(Unit.Default); shutdown.OnCompleted(); disposed = true; } }
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."); }
/// <summary> /// Handles send completion (including SendCloseFromClient). /// </summary> protected void HandleSendFinished(bool success) { bool delayCompletion = false; AsyncSubject <Unit> origTcs = null; lock (myLock) { if (!success && !finished && IsClient) { // We should be setting this only once per call, following writes will be short circuited // because they cannot start until the entire call finishes. GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed); // leave streamingWriteTcs set, it will be completed once call finished. isStreamingWriteCompletionDelayed = true; delayCompletion = true; } else { origTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } if (!success) { if (!delayCompletion) { if (IsClient) { GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient origTcs.OnError(GetRpcExceptionClientOnly()); } else { origTcs.OnError(new IOException("Error sending from server.")); } } // if delayCompletion == true, postpone SetException until call finishes. } else { origTcs.OnNext(Unit.Default); origTcs.OnCompleted(); } }
public void HasObservers_OnCompleted() { var s = new AsyncSubject <int>(); Assert.IsFalse(s.HasObservers); var d = s.Subscribe(_ => { }); Assert.IsTrue(s.HasObservers); s.OnNext(42); Assert.IsTrue(s.HasObservers); s.OnCompleted(); Assert.IsFalse(s.HasObservers); }
public AsyncSubject <Unit> OpenTransition() { AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); var image = _transitionOpen.GetComponent <Image>(); image.enabled = true; image.material.SetFloat(ShaderProperties.FadeAmount, 1f); DOTween.To(() => image.material.GetFloat(ShaderProperties.FadeAmount), (x) => image.material.SetFloat(ShaderProperties.FadeAmount, x), -0.1f, 1f).Play().OnComplete(() => { image.enabled = false; subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
static void Main(string[] args) { //异步编程通常这么写 //Task<int> t = Task<int>.Factory.StartNew(() => 25); //int value = t.Result; //会给到异步编程的最后一个值 var sernsor = new AsyncSubject <double>(); sernsor.Inspect("async"); sernsor.OnNext(1.0); sernsor.OnNext(2.0); sernsor.OnCompleted(); }
private static IObservable <Unit> ConvertTokenToObservable(CancellationToken token) { var cancel = new AsyncSubject <Unit>(); if (token.IsCancellationRequested) { return(Observable.Throw <Unit>(new ArgumentException("Token is already cancelled"))); } token.Register(() => { cancel.OnNext(Unit.Default); cancel.OnCompleted(); }); return(cancel); }
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 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 AsyncSubject <Unit> Hide() { AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); _sprites.ForEach(x => { x.SpriteRenderer.DOFade(0, 0.4f).Play(); x.Ui.UiParent.GetComponent <CanvasGroup>().DOFade(0, 0.4f).Play(); }); ObservableUtils.Timer(60).Subscribe(_ => { subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
IObservable <ScreenPresenter> BackTransition(ScreenPresenter preview, ScreenPresenter next) { next.gameObject.SetActive(true); var subject = new AsyncSubject <ScreenPresenter> (); preview.OnBackOut() .SelectMany(_ => next.OnBackIn()) .Subscribe(_ => { }, () => { Destroy(preview.gameObject); subject.OnNext(next); subject.OnCompleted(); }); return(subject); }
public static void UnlessThereIsNone_ButAtLeastItFinishes() { var subject = new AsyncSubject <int>(); var consoleObserver = new ConsoleObserver <int>(); var subscription = subject.Subscribe(consoleObserver); var consoleObserver2 = new ConsoleObserver <int>(); var subscription2 = subject.Subscribe(consoleObserver2); subject.OnCompleted(); //This won't appear because of the contract of IObservable subject.OnNext(9); subscription.Dispose(); subscription2.Dispose(); }
public static void AsyncSubject() { Console.WriteLine("----------ASYNC SUBJECT(2)"); var subject = new AsyncSubject <int>(); subject.Subscribe(new Observer("A")); subject.OnNext(1); subject.OnNext(11); subject.OnNext(111); subject.Subscribe(new Observer("B")); subject.OnNext(2); subject.OnNext(3); subject.OnCompleted(); // important! (subject.OnError(new Exception())); subject.OnNext(4); Console.ReadKey(); }
public AsyncSubject <Unit> PoisonEffect(int uniqId, List <SkillDamages> damageses) { var targetTransform = BattleDictionary.GetTransformByUniqId(uniqId); AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); var poison = Instantiate((GameObject)Resources.Load("Prefabs/Status/Poison")); var poisonEffect = poison.GetComponent <SkillBehavior>(); poisonEffect.Play(damageses); poison.transform.localPosition = targetTransform.localPosition; ObservableUtils.Timer(200).Subscribe(_ => { subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
/// <summary> /// タイムラインを次に送る /// </summary> public AsyncSubject <Unit> TimelineNext() { AsyncSubject <Unit> subject = new AsyncSubject <Unit>(); TimelineCalc(); _timelineSchedule.Remove(_timelineSchedule.First()); var id = TimeLineForward(); _timelineView.DepopSchedule(); _timelineView.AddCard(BattleDictionary.GetTimelineById(_timelineData, id)).Subscribe(_ => { subject.OnNext(Unit.Default); subject.OnCompleted(); }); return(subject); }
internal IObservable <IParseResult <TResult> > Parse( ICollection <IObservableParser <TSource, TResult> > except, IObservableCursor <TSource> source) { Contract.Requires(except != null); Contract.Requires(!except.IsReadOnly); Contract.Requires(source != null); Contract.Ensures(Contract.Result <IObservable <IParseResult <TResult> > >() != null); return(Observable.Defer(() => { var completed = new AsyncSubject <Unit>(); bool hasResult = false; return parsers.Except(except).Select( parser => Observable.Create <IParseResult <TResult> >( observer => { return parser.Parse(source).SubscribeSafe( result => { if (!hasResult) { hasResult = true; except.Add(parser); } observer.OnNext(result); }, observer.OnError, () => { if (hasResult) { completed.OnNext(new Unit()); completed.OnCompleted(); } observer.OnCompleted(); }); })) .Concat() .TakeUntil(completed); })); }
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); }
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 void scheduler_is_used_to_distribute_values() { ManualScheduler scheduler = new ManualScheduler(); AsyncSubject<int> subject = new AsyncSubject<int>(scheduler); StatsObserver<int> statsA = new StatsObserver<int>(); subject.OnNext(1); subject.OnNext(2); subject.OnNext(3); subject.OnCompleted(); subject.Subscribe(statsA); Assert.IsFalse(statsA.NextCalled); scheduler.RunNext(); Assert.IsTrue(statsA.NextCalled); }
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); }
public void next_and_complete_are_scheduled_separately() { ManualScheduler scheduler = new ManualScheduler(); AsyncSubject<int> subject = new AsyncSubject<int>(scheduler); StatsObserver<int> statsA = new StatsObserver<int>(); subject.OnNext(1); subject.OnNext(2); subject.OnNext(3); subject.OnCompleted(); subject.Subscribe(statsA); Assert.AreEqual(1, scheduler.QueueSize); scheduler.RunNext(); Assert.IsTrue(statsA.NextCalled); Assert.IsFalse(statsA.CompletedCalled); Assert.AreEqual(1, scheduler.QueueSize); scheduler.RunNext(); Assert.IsTrue(statsA.CompletedCalled); }
public void PhotosetsGetInfoAsyncTest() { Flickr f = TestData.GetInstance(); var photoset = f.PhotosetsGetList(TestData.TestUserId).First(); var w = new AsyncSubject<FlickrResult<Photoset>>(); f.PhotosetsGetInfoAsync(photoset.PhotosetId, r => { w.OnNext(r); w.OnCompleted(); }); var result = w.Next().First(); }
public void PhotosetsGetPhotosAsyncTest() { Flickr f = TestData.GetInstance(); var photoset = f.PhotosetsGetList(TestData.TestUserId).First(); var w = new AsyncSubject<FlickrResult<PhotosetPhotoCollection>>(); f.PhotosetsGetPhotosAsync(photoset.PhotosetId, PhotoSearchExtras.All, PrivacyFilter.PublicPhotos, 1, 50, MediaType.All, r => { w.OnNext(r); w.OnCompleted(); }); var result = w.Next().First(); Assert.IsFalse(result.HasError); }
public void HasObservers_OnCompleted() { var s = new AsyncSubject<int>(); Assert.IsFalse(s.HasObservers); var d = s.Subscribe(_ => { }); Assert.IsTrue(s.HasObservers); s.OnNext(42); Assert.IsTrue(s.HasObservers); s.OnCompleted(); Assert.IsFalse(s.HasObservers); }
public void GetResult_Context() { var x = new AsyncSubject<int>(); var ctx = new MyContext(); var e = new ManualResetEvent(false); new Thread(() => { SynchronizationContext.SetSynchronizationContext(ctx); var a = x.GetAwaiter(); a.OnCompleted(() => { e.Set(); }); }).Start(); x.OnNext(42); x.OnCompleted(); e.WaitOne(); Assert.IsTrue(ctx.ran); }
private void GetResult_Blocking(AsyncSubject<int> s) { Assert.IsFalse(s.IsCompleted); var e = new ManualResetEvent(false); new Thread(() => { e.WaitOne(); s.OnNext(42); s.OnCompleted(); }).Start(); var y = default(int); var t = new Thread(() => { y = s.GetResult(); }); t.Start(); while (t.ThreadState != ThreadState.WaitSleepJoin) ; e.Set(); t.Join(); Assert.AreEqual(42, y); Assert.IsTrue(s.IsCompleted); }
public void GetResult_Empty() { var s = new AsyncSubject<int>(); s.OnCompleted(); ReactiveAssert.Throws<InvalidOperationException>(() => s.GetResult()); }