public Harmonizer(With.Messaging.Service.IEndpoint serviceEndpoint) { _serviceEndpoint = serviceEndpoint; _messages = new Subject<With.Message.IMessage>(); _messageObservable = _messages.Publish(); }
public KanColleProxy() { this.compositeDisposable = new MultipleDisposable(); this.connectableSessionSource = Observable .FromEvent<Action<Session>, Session>( action => action, h => HttpProxy.AfterSessionComplete += h, h => HttpProxy.AfterSessionComplete -= h) .Publish(); this.apiSource = this.connectableSessionSource .Where(s => s.Request.PathAndQuery.StartsWith("/kcsapi")) .Where(s => s.Response.MimeType.Equals("text/plain")) #region .Do(debug) #if DEBUG .Do(session => { Debug.WriteLine("=================================================="); Debug.WriteLine("Nekoxy session: "); Debug.WriteLine(session); Debug.WriteLine(""); }) #endif #endregion .Publish(); }
static CountdownModelBase() { r_Interval = Observable.Interval(TimeSpan.FromSeconds(1.0)).Publish(); r_Interval.Connect(); LastOneMinute = TimeSpan.FromMinutes(1.0); }
public KanColleProxy() { this.compositeDisposable = new LivetCompositeDisposable(); this.connectableSessionSource = Observable .FromEvent<SessionStateHandler, Session>( action => new SessionStateHandler(action), h => FiddlerApplication.AfterSessionComplete += h, h => FiddlerApplication.AfterSessionComplete -= h) .Publish(); this.apiSource = this.connectableSessionSource .Where(s => s.PathAndQuery.StartsWith("/kcsapi") && s.oResponse.MIMEType.Equals("text/plain")) .SynchronizeFIFO((a, b, c) => Synchronize) #region .Do(debug) #if DEBUG .Do(session => { Debug.WriteLine("=================================================="); Debug.WriteLine("Fiddler session: "); Debug.WriteLine(session); Debug.WriteLine(""); }) #endif #endregion .Publish(); }
public PodcastItemsLoader(SyndicationFeed feed) { _feed = feed; _observable = Observable.Defer(() => feed.Items.Where(item => item.IsPodcast()) .ToObservable() //.Do(item => item.SourceFeed = feed) .Select(item => new PodcastItemViewModel(item))) .Publish(); }
public Aggregator(string counterCategoryFilter, string counterNameFilter, string aggregationType, string aggregationParameters, Type valuesDataType) { _aggregationOperation = AggregationOperationFactory.Create(valuesDataType, aggregationType, aggregationParameters); _counterCategoryFilter = counterCategoryFilter; _counterNameFilter = counterNameFilter; _valuesDataType = valuesDataType; _seq = new MovingWindowSequence(1000, 1000*5); _logEventBuffer = _eventSubject.Window(_seq.BufferOpenings, _seq.ClosingWindowSequenceSelector).Publish(); _logEventBuffer.Connect(); }
public MemoryLogReader(string logName, IScheduler scheduler = null) { _logName = logName; scheduler = scheduler ?? TaskPoolScheduler.Default; _target = FindTarget(); _connectObservable = Observable.Interval(TimeSpan.FromSeconds(1), scheduler) .Select(x => ReadTargetEntries()) .Publish(); _disposable = _connectObservable.Connect(); }
public HeartbeatService(TimeSpan interval, ISchedulerService schedulerService) { using (Duration.Measure(Logger, "Constructor - " + GetType() .Name)) { _listen = Observable.Interval(interval, schedulerService.TaskPool) .AsUnit() .Publish(); _listen.Connect() .DisposeWith(this); } }
public IObservable <BitmapSource> GetFrames() { if (_frames == null) { _frames = Observable .Interval(TimeSpan.FromMilliseconds(1000 / FramesPerSecond)) .Select(x => CaptureDMD()) .Where(bmp => bmp != null) .Publish(); StartPolling(); } return(_frames); }
public IObservable <byte[]> GetGray4Frames() { if (_framesGray4 == null) { _framesGray4 = Observable .Interval(TimeSpan.FromMilliseconds(1000 / FramesPerSecond)) .Select(x => CaptureDMDGray4()) .Where(frame => frame != null) .Publish(); StartPolling(true); } return(_framesGray4); }
public MemoryLogReader(string logName, IScheduler scheduler = null) { _logName = logName; scheduler = scheduler ?? TaskPoolScheduler.Default; _target = FindTarget(); _connectObservable = Observable.Interval(TimeSpan.FromSeconds(1), scheduler) .Select(x => ReadTargetEntries()) .Publish(); _disposable = _connectObservable.Connect(); }
/// <summary> /// Hotなので、Observableが分岐する /// </summary> private void ExcutePublishHot() { IConnectableObservable <int> stream = Observable .Range(1, 3) .Do(x => Debug.Log("Hot Value : " + x)) // Hot変換 .Publish(); stream.Subscribe(); stream.Subscribe(); // ストリームを稼働 stream.Connect(); }
private void CreatePositionUpdater() { this._positionPoller = Observable .Interval(this._positionUpdatesInterval, TaskPoolScheduler.Default) // TODO: use taskpool scheduler? .Select(_ => this._soundOut?.WaveSource?.GetPosition()) .DistinctUntilChanged() // TODO: does .DistinctUntilChanged() filter equal value in respect to a subscription which contains a startwith like the one here below? .Publish(); this._positionPoller .StartWith(this._soundOut?.WaveSource?.GetPosition()) // startwith here in this block so it gets current position of when subscription is connected .Subscribe(position => this._positionSubject.OnNext(position)) .DisposeWith(this._playerScopeDisposables); }
/// <summary> /// Monitor IConnectableObservable stream /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> /// <param name="orderingIndex">Index of the ordering.</param> /// <param name="surrogate">The surrogate.</param> /// <param name="keywords">The keywords.</param> /// <returns></returns> public static IConnectableObservable <T> Monitor <T>( this IConnectableObservable <T> instance, string name, double orderingIndex, IMonitorSurrogate <T> surrogate, params string[] keywords) { var monitor = new MonitorOperator <T>( name, orderingIndex, surrogate, keywords); var watcher = monitor.AttachTo(instance); return(watcher); }
protected IObservable <TimeInterval <float> > FadeOutActionAsObservable( PlayerActor actor, int sex, Transform t, ActionPoint actionPoint) { if (Object.op_Inequality((Object)t, (Object)null)) { Vector3 position = actor.Position; Quaternion rotation = actor.Rotation; ActionPointInfo outInfo; actionPoint.TryGetPlayerActionPointInfo(actor.EventKey, out outInfo); Dictionary <int, Dictionary <int, PlayState> > dictionary1; Dictionary <int, PlayState> dictionary2; PlayState playState; if (Singleton <Resources> .Instance.Animation.PlayerActionAnimTable.TryGetValue(sex, out dictionary1) && dictionary1.TryGetValue(outInfo.eventID, out dictionary2) && dictionary2.TryGetValue(outInfo.poseID, out playState)) { IConnectableObservable <TimeInterval <float> > iconnectableObservable = (IConnectableObservable <TimeInterval <float> >)Observable.Publish <TimeInterval <float> >((IObservable <M0>)Observable.FrameTimeInterval <float>((IObservable <M0>)ObservableEasing.Linear(playState.MainStateInfo.OutStateInfo.FadeSecond, false), false)); iconnectableObservable.Connect(); switch (playState.DirectionType) { case 0: if (playState.MainStateInfo.OutStateInfo.EnableFade) { ObservableExtensions.Subscribe <TimeInterval <float> >((IObservable <M0>)iconnectableObservable, (Action <M0>)(x => { actor.Position = Vector3.Lerp(position, t.get_position(), ((TimeInterval <float>) ref x).get_Value()); actor.Rotation = Quaternion.Slerp(rotation, t.get_rotation(), ((TimeInterval <float>) ref x).get_Value()); })); break; } actor.Position = t.get_position(); actor.Rotation = t.get_rotation(); break; case 1: Quaternion lookRotation = Quaternion.LookRotation(Vector3.op_Subtraction(actionPoint.Position, position)); if (playState.MainStateInfo.OutStateInfo.EnableFade) { ObservableExtensions.Subscribe <TimeInterval <float> >((IObservable <M0>)iconnectableObservable, (Action <M0>)(x => actor.Rotation = Quaternion.Slerp(rotation, lookRotation, ((TimeInterval <float>) ref x).get_Value()))); break; } actor.Rotation = lookRotation; break; } return((IObservable <TimeInterval <float> >)iconnectableObservable); } } return((IObservable <TimeInterval <float> >)Observable.Empty <TimeInterval <float> >()); }
public void Run(CancellationToken cancellationToken = default) { // create the Observable, use Publish so frame are all published to all subcribers _observable = Observable.Create <Frame>(observer => Execute(observer, cancellationToken)).Publish(); // connect the observerable (start running) var subscription = _observable.Connect(); // when canceled dispose subscription cancellationToken.Register(() => { subscription.Dispose(); }); }
public MemoryService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null) { _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default; _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current; _logger = LogManager.GetCurrentClassLogger(); _countersObservable = Observable.Create <Counters>(x => CreateCounters(x)) .SubscribeOn(_taskPoolScheduler) .CombineLatest(BufferedDispatcherIdle(TimeSpan.FromSeconds(1)), (x, y) => x) .Replay(1); _disposable = _countersObservable.Connect(); }
public MemoryService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null) { _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default; _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current; _logger = LogManager.GetCurrentClassLogger(); _countersObservable = Observable.Create<Counters>(x => CreateCounters(x)) .SubscribeOn(_taskPoolScheduler) .CombineLatest(BufferedDispatcherIdle(TimeSpan.FromSeconds(1)), (x, y) => x) .Replay(1); _disposable = _countersObservable.Connect(); }
protected override void OnBeforeStart() { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type CommCommandList.\u003COnBeforeStart\u003Ec__AnonStorey9 startCAnonStorey9 = new CommCommandList.\u003COnBeforeStart\u003Ec__AnonStorey9(); // ISSUE: reference to a compiler-generated field startCAnonStorey9.\u0024this = this; if (!Application.get_isPlaying()) { return; } this._scrollCylinder.enableInternalScroll = false; // ISSUE: reference to a compiler-generated method ObservableExtensions.Subscribe <bool>((IObservable <M0>) this.OnActiveChangedAsObservable(), (Action <M0>) new Action <bool>(startCAnonStorey9.\u003C\u003Em__0)); // ISSUE: reference to a compiler-generated method ObservableExtensions.Subscribe <int>((IObservable <M0>) this.OnSelectIDChagnedAsObservable(), (Action <M0>) new Action <int>(startCAnonStorey9.\u003C\u003Em__1)); IConnectableObservable <long> iconnectableObservable = (IConnectableObservable <long>)Observable.Publish <long>(Observable.TakeUntilDestroy <long>((IObservable <M0>)Observable.EveryUpdate(), ((Component)this).get_gameObject())); iconnectableObservable.Connect(); // ISSUE: reference to a compiler-generated method // ISSUE: reference to a compiler-generated method ObservableExtensions.Subscribe <long>(Observable.Where <long>((IObservable <M0>)iconnectableObservable, (Func <M0, bool>) new Func <long, bool>(startCAnonStorey9.\u003C\u003Em__2)), (Action <M0>) new Action <long>(startCAnonStorey9.\u003C\u003Em__3)); ActionIDDownCommand actionIdDownCommand1 = new ActionIDDownCommand() { ActionID = ActionID.Cancel }; // ISSUE: method pointer actionIdDownCommand1.TriggerEvent.AddListener(new UnityAction((object)startCAnonStorey9, __methodptr(\u003C\u003Em__4))); this._actionCommands.Add(actionIdDownCommand1); ActionIDDownCommand actionIdDownCommand2 = new ActionIDDownCommand() { ActionID = ActionID.MouseRight }; // ISSUE: method pointer actionIdDownCommand2.TriggerEvent.AddListener(new UnityAction((object)startCAnonStorey9, __methodptr(\u003C\u003Em__5))); this._actionCommands.Add(actionIdDownCommand2); this._nodePool = new CommCommandList.NodePool() { Source = ((Component)this._node).get_gameObject() }; // ISSUE: reference to a compiler-generated field startCAnonStorey9.iconTable = Singleton <Resources> .Instance.itemIconTables; // ISSUE: reference to a compiler-generated field startCAnonStorey9.commonDefine = Singleton <Resources> .Instance.CommonDefine; // ISSUE: reference to a compiler-generated method ObservableExtensions.Subscribe <Unit>((IObservable <M0>)Singleton <Resources> .Instance.LoadMapResourceStream, (Action <M0>) new Action <Unit>(startCAnonStorey9.\u003C\u003Em__6)); }
public DataClockProvider(IScheduler scheduler) { _scheduler = scheduler; _dataClockSource = Observable.Interval(DataClockProviderConfig.ClockInterval, _scheduler) .TakeWhile(_ => !_isDisposed) .Select(GetDataClock) .Multicast(_dataClockSubject); // Defer connection of IConnectObservable till very first subscription _dataClockObservable = Observable.Defer(StartOnSubscription); Logger.Info($"Initial Data Clock: {_sourceClock + _dataLimit}"); }
public EventStoreCatchUpSubscriptionObservable(Lazy <IEventStoreConnection> connection, Position?lastCheckpoint, int maxLiveQueueMessage, UserCredentials userCredentials, TraceWriter trace) { _lastCheckpoint = lastCheckpoint; _userCredentials = userCredentials; _trace = trace; _connection = connection; _maxLiveQueueMessage = maxLiveQueueMessage; _subject = new Subject <ResolvedEvent>(); _observable = _subject.Publish(); }
public IObservable <ColoredFrame> GetColoredGray2Frames() { if (_framesColoredGray2 != null) { return(_framesColoredGray2); } _framesColoredGray2 = Observable .Interval(TimeSpan.FromMilliseconds(1000 / FramesPerSecond)) .Select(x => CaptureDMD()) .Where(frame => frame != null) .Publish(); StartPolling(); return(_framesColoredGray2); }
/// <summary> /// Initializes a new instance of the <see cref="ModelObservableValidationBase{TViewModel}"/> class. /// </summary> /// <param name="viewModel">ViewModel instance.</param> /// <param name="validityObservable">Func to define if the viewModel is valid or not.</param> /// <param name="messageFunc">Func to define the validation error message based on the viewModel and validityObservable values.</param> protected ModelObservableValidationBase( TViewModel viewModel, Func <TViewModel, IObservable <bool> > validityObservable, Func <TViewModel, bool, ValidationText> messageFunc) { _disposables.Add(_lastValidationStateSubject.Do(s => { _isValid = s.IsValid; _text = s.Text; }).Subscribe()); _validityConnectedObservable = Observable.Defer(() => validityObservable(viewModel)) .Select(v => new ValidationState(v, messageFunc(viewModel, v), this)) .Multicast(_lastValidationStateSubject); }
/// <summary> /// Initializes a new instance of the <see cref="ObservableValidationBase{TViewModel, TValue}"/> class. /// </summary> /// <param name="observable">Observable that updates the view model property validity.</param> protected ObservableValidationBase(IObservable <IValidationState> observable) { _isValidSubject .Do(state => { _isValid = state.IsValid; _text = state.Text; }) .Subscribe() .DisposeWith(_disposables); _validityConnectedObservable = Observable .Defer(() => observable) .Multicast(_isValidSubject); }
public Store(Reducer <TApplicationState> reducer, TApplicationState initialState = default(TApplicationState), params Interceptor <TApplicationState>[] interceptors) { dispatcher = new Subject <object>(); storeStateStream = GetStateObservable(reducer, initialState); storeStateStream.Connect(); //for initialState, might be set in reducer Dispatch <object>(null); foreach (var interceptor in interceptors) { interceptor.Initialize(this, dispatcher); } }
private void Activate() { if (!_isConnected) { _connectedChange = GetValidationChangeObservable().Do(v => { _isValid = v.IsValid; _text = v.Text; }).Replay(1); _disposables.Add(_connectedChange.Connect()); _isConnected = true; } }
public void HotObservable() { /* Convert the previous cold observable to a hot observable through the use of the Publish operator. * Publish operator, which returns an IConnectableObservable instance we name hot. * The Publish operator provides a mechanism to share subscriptions by broadcasting a single subscription * to multiple subscribers. hot acts as a proxy and subscribes to source, then as it receives values from * source, pushes them to its own subscribers. To establish a subscription to the backing source and start * receiving values, we use the IConnectableObservable.Connect() method. Since IConnectableObservable * inherits IObservable, we can use Subscribe to subscribe to this hot sequence even before it starts running. * Notice that in the example, the hot sequence has not been started when subscription1 subscribes to it. * Therefore, no value is pushed to the subscriber. After calling Connect, values are then pushed to subscription1. * After a delay of 3 seconds, subscription2 subscribes to hot and starts receiving the values immediately from * the current position (3 in this case) until the end. */ Console.WriteLine("Hot Observable"); Console.WriteLine($"Current Time: {DateTime.UtcNow}"); var source = Observable.Interval(TimeSpan.FromSeconds(1)); IConnectableObservable <long> hot = source.Publish(); // Convert to hot sequence var sub1 = hot.Subscribe( x => Console.WriteLine("Observer 1: OnNext: {0}", x), ex => Console.WriteLine("Observer 1: OnError: {0}", ex.Message), () => Console.WriteLine("Observer 1: OnCompleted")); Console.WriteLine("Current Time after 1st subscription: " + DateTime.Now); Thread.Sleep(3000); // idle for 3 seconds hot.Connect(); // hot is connected to source and start pushing values to subscribers Console.WriteLine("Current Time after Connect: " + DateTime.Now); Thread.Sleep(3000); // idle for 3 seconds Console.WriteLine("Current Time just before 2nd subscription: " + DateTime.Now); var sub2 = hot.Subscribe( // value will immediately be pushed to second subscription x => Console.WriteLine("Observer 2: OnNext: {0}", x), ex => Console.WriteLine("Observer 2: OnError: {0}", ex.Message), () => Console.WriteLine("Observer 2: OnCompleted")); Console.ReadLine(); sub1.Dispose(); sub2.Dispose(); }
public IObservable <TimeInterval <float>[]> Close() { Vector2 diff = Vector2.op_Subtraction(this._source, this._destination); IConnectableObservable <TimeInterval <float> > iconnectableObservable1 = (IConnectableObservable <TimeInterval <float> >)Observable.Publish <TimeInterval <float> >((IObservable <M0>)Observable.FrameTimeInterval <float>((IObservable <M0>)ObservableEasing.Create(Tween.MotionFunctionTable.get_Item(this._motionTypes.@out), 0.3f, true), true)); IConnectableObservable <TimeInterval <float> > iconnectableObservable2 = (IConnectableObservable <TimeInterval <float> >)Observable.Publish <TimeInterval <float> >((IObservable <M0>)Observable.FrameTimeInterval <float>((IObservable <M0>)ObservableEasing.Create(Tween.MotionFunctionTable.get_Item(this._alphaFadingTypes.@out), 0.3f, true), true)); iconnectableObservable1.Connect(); iconnectableObservable2.Connect(); ObservableExtensions.Subscribe <TimeInterval <float> >((IObservable <M0>)iconnectableObservable1, (System.Action <M0>)(x => this.SetPosition(diff, ((TimeInterval <float>) ref x).get_Value()))); ObservableExtensions.Subscribe <TimeInterval <float> >((IObservable <M0>)iconnectableObservable2, (System.Action <M0>)(x => this._canvasGroup.set_alpha(1f - ((TimeInterval <float>) ref x).get_Value()))); return((IObservable <TimeInterval <float>[]>)Observable.WhenAll <TimeInterval <float> >((IObservable <M0>[]) new IObservable <TimeInterval <float> >[2] { (IObservable <TimeInterval <float> >)iconnectableObservable1, (IObservable <TimeInterval <float> >)iconnectableObservable2 })); }
public static void DelegateBasedHotSource() { IObservable <char> singularHotSource = Observable.Create( (Func <IObserver <char>, IDisposable>)(obs => { while (true) { obs.OnNext(Console.ReadKey(true).KeyChar); } })); IConnectableObservable <char> keySource = singularHotSource.Publish(); keySource.Subscribe(new MySubscriber <char>()); keySource.Subscribe(new MySubscriber <char>()); }
static AsyncSubject<TSource> RunAsync<TSource>(IConnectableObservable<TSource> source, CancellationToken cancellationToken) { var s = new AsyncSubject<TSource>(); if (cancellationToken.IsCancellationRequested) { return Cancel(s, cancellationToken); } var d = source.Subscribe(s); var c = source.Connect(); if (cancellationToken.CanBeCanceled) { RegisterCancelation(s, StableCompositeDisposable.Create(d, c), cancellationToken); } return s; }
public Instance(IParser packetParser, IPEndPoint localPacketEndpoint) { _packetParser = packetParser; _localPacketEndpoint = localPacketEndpoint; _udpClient = new UdpClient(); _udpClient.Client.Bind(_localPacketEndpoint); _readings = Observable.FromAsync(_udpClient.ReceiveAsync).Repeat() .Select(result => result.Buffer) .Select(Encoding.ASCII.GetString) .Do(Instrumentation.Packet.Endpoint.Receive) .SelectMany(_packetParser.GetReadings) .Do(Instrumentation.Packet.Endpoint.Reading) .Publish(); }
public Instance(IParser packetParser, IPEndPoint localPacketEndpoint) { _packetParser = packetParser; _localPacketEndpoint = localPacketEndpoint; _udpClient = new UdpClient(); _udpClient.Client.Bind(_localPacketEndpoint); _readings = Observable.FromAsync(_udpClient.ReceiveAsync).Repeat() .Select(result => result.Buffer) .Select(Encoding.ASCII.GetString) .Do(Instrumentation.Packet.Endpoint.Receive) .SelectMany(_packetParser.GetReadings) .Do(Instrumentation.Packet.Endpoint.Reading) .Publish(); }
private TimerSingleton() { DateTime d = DateTime.Now; var interval = Observable.Interval(TimeSpan.FromSeconds(5)) .StartWith(default(long)); Time = interval .Select(_ => DateTime.Now - d) .ObserveOn(RxApp.MainThreadScheduler) .Publish(); Date = interval .Select(_ => DateTime.Now) .ObserveOn(RxApp.MainThreadScheduler) .Publish(); }
/// <summary> /// Monitor IConnectableObservable stream /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> /// <param name="orderingIndex">Index of the ordering.</param> /// <param name="surrogate">The surrogate.</param> /// <param name="setting"></param> /// <returns></returns> public static IConnectableObservable <T> Monitor <T>( this IConnectableObservable <T> instance, string name, double?orderingIndex, Func <T, object> surrogate, VisualRxPublishersSettings setting = null) { setting = setting ?? VisualRxPublishersSettings.Default; double order = orderingIndex ?? Interlocked.Increment(ref _order); var monitor = new StreamChannel <T>( setting, name, order, surrogate); var watcher = monitor.AttachTo(instance); return(watcher); }
public IdleService(ISchedulerService schedulerService) { var mainWindow = Application.Current.MainWindow; if (mainWindow == null) { throw new Exception("Main window has not been created yet!"); } _idleObservable = Observable.FromEventPattern(h => mainWindow.Dispatcher.Hooks.DispatcherInactive += h, h => mainWindow.Dispatcher.Hooks.DispatcherInactive -= h, schedulerService.TaskPool) .Publish(); _disposable = _idleObservable.Connect(); _disposable = Disposable.Empty; }
/// <summary> /// Initializes a new instance of the <see cref="ValidationContext"/> class. /// </summary> /// <param name="scheduler">Optional scheduler to use for the properties. Uses the main thread scheduler by default.</param> public ValidationContext(IScheduler scheduler = null) { #if NET_461 || NETSTANDARD scheduler = scheduler ?? RxApp.TaskpoolScheduler; #else scheduler = scheduler ?? RxApp.MainThreadScheduler; #endif var validationChangedObservable = _validationSource.Connect(); // Connect SourceList to read only observable collection. validationChangedObservable .ObserveOn(scheduler) .Bind(out _validations) .Subscribe(); // Publish the current validation state. _disposables.Add(_validSubject .StartWith(true) .ToProperty(this, m => m.IsValid, out _isValid, scheduler: scheduler)); // When a change occurs in the validation state, publish the updated validation text. _disposables.Add(_validSubject .StartWith(true) .Select(_ => BuildText()) .ToProperty(this, m => m.Text, out _validationText, new ValidationText(), scheduler: scheduler)); // Publish the current validation state. _disposables.Add(_validSubject .Select(_ => new ValidationState(IsValid, BuildText(), this)) .Do(vc => _validationStatusChange.OnNext(vc)) .Subscribe()); // Observe the defined validations and whenever there is a change publish the current validation state. _validationConnectable = validationChangedObservable .ToCollection() .StartWithEmpty() .Select(validations => validations .Select(v => v.ValidationStatusChange) .Merge() .Select(_ => Unit.Default) .StartWith(Unit.Default)) .Switch() .Select(_ => GetIsValid()) .Multicast(_validSubject); }
public WsIQClientRx() { // TODO INJECT _ws = new WebSocketWrapper(); _epoch = new Epoch(); _randomNumbers = new RandomNumbers(); MessagesFeed = Observable .FromEventPattern <OnMessageEventHandler, WsRecievemessageEventArgs>( h => _ws.OnMessage += h, h => _ws.OnMessage -= h) //.ObserveOn(NewThreadScheduler.Default) .Map((e) => { var serializedMessage = e.EventArgs.Message; var iQmessage = JsonConvert.DeserializeObject <IQOptionMessage>(serializedMessage); return(iQmessage); }); _onConnection = Observable .FromEventPattern <OnConnectedEventHandler, EventArgs>( h => _ws.OnConnected += h, h => _ws.OnConnected -= h) .Map(e => e.EventArgs) .Replay(); _onConnectionConnection = _onConnection.Connect(); //TODO DO THIS IN THE IQCLient _ssidDualChannel = new SsidPublisherChannel(this); _heartBeatDualChannel = new HeartBeatDualChannel(this); _wsMessagesSubscription = _heartBeatDualChannel.ChannelFeed .Map(heartbeat => _heartBeatDualChannel.SendMessage(new HeartBeatOutputMessage(_epoch.EpochMilliSeconds, heartbeat.HeartbeatTime))) .Subscribe(); _candleGeneratedDualChannel = new CandleGeneratedDualChannel(this); _serverTimeSync = new TimeSyncListenerChannel(this); _profileChannel = new ProfileListenerChannel(this); _listInfoDataChannelListener = new ListInfoDataListenerChannel(this); _buyV2ChannelPublisher = new BuyV2Channel(this, _epoch); }
/// <summary> /// Hotは分岐できる /// </summary> private void HotBranch() { // 1~3を発行するストリーム IConnectableObservable <int> stream = Observable .Range(1, 3) .Select(x => { Debug.Log("Hot : " + x); return(x); }) // Hot変換オペレータ .Publish(); // ストリームの稼働開始 stream.Connect(); stream.Subscribe(); stream.Subscribe(); }
private static void TestConnectMultipleTimes() { IConnectableObservable <long> proxy = Observable.Interval(TimeSpan.FromSeconds(0.5)).Publish(); proxy.Subscribe(new ConsolePrintObserver <long>()); proxy.Subscribe(new ConsolePrintObserver <long>("q", ConsoleColor.DarkGreen)); for (int index = 0; index < 2; index++) { // everytime connected, the proxy subscribed to the underlying cold observable // the underlying cold observable will start from beginning once again using (proxy.Connect()) { Helper.Pause(); } }//for }
public DiagnosticsService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null) { _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default; _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current; _countersObservable = Observable.Create<Counters>(x => CreateCounters(x)) .SubscribeOn(_taskPoolScheduler) .Replay(1); _assemblyObservable = AssemblyLoaded() .SubscribeOn(_taskPoolScheduler) .Merge(Observable.Return(AppDomain.CurrentDomain.GetAssemblies()).SelectMany(x => x)) .Replay(); _disposable = new CompositeDisposable { _countersObservable.Connect(), _assemblyObservable.Connect() }; }
public ConnectionStatusMonitor(IEventStoreConnection connection) { var connectedChanged = Observable.FromEventPattern<ClientConnectionEventArgs>(h => connection.Connected += h, h => connection.Connected -= h) .Select(_ => ConnectionStatus.Connected); var disconnectedChanged = Observable.FromEventPattern<ClientConnectionEventArgs>(h => connection.Disconnected += h, h => connection.Disconnected -= h) .Select(_ => ConnectionStatus.Disconnected); var reconnectingChanged = Observable.FromEventPattern<ClientReconnectingEventArgs>(h => connection.Reconnecting += h, h => connection.Reconnecting -= h) .Select(_ => ConnectionStatus.Connecting); _connectionInfoChanged = Observable.Merge(connectedChanged, disconnectedChanged, reconnectingChanged) .Scan(ConnectionInfo.Initial, UpdateConnectionInfo) .StartWith(ConnectionInfo.Initial) .Replay(1); _connection = _connectionInfoChanged.Connect(); }
public BluetoothProfileActivator(IBluetoothService bluetoothService, IPersonalizationSettings personalizationSettings, ISchedulerProvider schedulerProvider, ILoggerFactory loggerFactory) { _bluetoothService = bluetoothService; _personalizationSettings = personalizationSettings; _schedulerProvider = schedulerProvider; _logger = loggerFactory.CreateLogger(GetType()); _bluetoothEventLoop = _schedulerProvider.CreateEventLoopScheduler("BluetoothActivator"); _logger.Verbose("BluetoothProfileActivator.ctor();"); _profileActivated = _bluetoothService.IdentitiesActivated(_bluetoothEventLoop) .Retry() .Repeat() .Log(_logger, "IdentitiesActivated") .Select(Translate) .Publish(); //HACK: Avoid work in the ctor. Can be smart here using SelectMany on the IsEnabled + Connecting when ProfileActivated is subscribed to. -LC if (_bluetoothService.IsSupported && IsEnabled) _connection.Disposable = _profileActivated.Connect(); }
public EmbeddedEventStoreConnectionFactory() { var noIp = new IPEndPoint(IPAddress.None, 0); _vnode = EmbeddedVNodeBuilder.AsSingleNode() .RunInMemory() .WithExternalTcpOn(noIp) .WithInternalTcpOn(noIp) .WithExternalHttpOn(noIp) .WithInternalHttpOn(noIp) .Build(); _status = Observable.FromEventPattern<VNodeStatusChangeArgs>( h => _vnode.NodeStatusChanged += h, h => _vnode.NodeStatusChanged -= h) .Select(e => e.EventArgs.NewVNodeState) .Log(new ConsoleLogger(), "VNode.State") .Publish(VNodeState.Unknown); _statusSubscription.Disposable = _status.Connect(); _vnode.Start(); _conn = EmbeddedEventStoreConnection.Create(_vnode); }
void InitializeCommunicator(int rpHostProcessID) { r_Communicator = new MemoryMappedFileCommunicator($"Sakuno/HeavenlyWind({rpHostProcessID})", 4096); r_Communicator.ReadPosition = 0; r_Communicator.WritePosition = 2048; r_Messages = r_Communicator.GetMessageObservable().ObserveOnDispatcher().Publish(); r_Messages.Connect(); r_Communicator.StartReader(); r_Messages.Subscribe(CommunicatorMessages.ClearCache, _ => r_BrowserProvider?.ClearCache(false)); r_Messages.Subscribe(CommunicatorMessages.ClearCacheAndCookie, _ => r_BrowserProvider?.ClearCache(true)); r_Messages.Subscribe(CommunicatorMessages.GoBack, _ => r_Browser?.GoBack()); r_Messages.Subscribe(CommunicatorMessages.GoForward, _ => r_Browser?.GoForward()); r_Messages.Subscribe(CommunicatorMessages.Navigate, rpUrl => r_Browser?.Navigate(rpUrl)); r_Messages.Subscribe(CommunicatorMessages.Refresh, _ => r_Browser?.Refresh()); r_Messages.Subscribe(CommunicatorMessages.SetZoom, r => { r_Zoom = double.Parse(r); r_Browser?.SetZoom(r_Zoom); r_Communicator.Write(CommunicatorMessages.InvalidateArrange); }); r_Messages.Subscribe(CommunicatorMessages.ResizeBrowserToFitGame, _ => { r_Container.Width = GameConstants.GameWidth * r_Zoom / DpiUtil.ScaleX / DpiUtil.ScaleX; r_Container.Height = GameConstants.GameHeight * r_Zoom / DpiUtil.ScaleY / DpiUtil.ScaleY; r_Communicator.Write(CommunicatorMessages.InvalidateArrange); }); InitializeScreenshotMessagesSubscription(); }
public async Task LoginAsync(UserStatus initialStatus = UserStatus.Online) { await @lock.WriterLockAsync(); try { if (IsLoggedIn) return; IConnection connection = null; ConnectionStream stream = null; CommandReader reader = null; CommandWriter writer = null; ResponseTracker responseTracker = null; IConnectableObservable<Command> commands = null; IDisposable commandsDisposable = null; int transferCount = 0; SocketEndPoint endPoint = SocketEndPoint.Parse("messenger.hotmail.com:1863"); string authTicket = null; while (authTicket == null) { connection = new SocketConnection(); await connection.ConnectAsync(endPoint); stream = new ConnectionStream(connection); writer = new CommandWriter(stream); reader = new CommandReader(stream, new Dictionary<string, Type> { { "VER", typeof(VersionCommand) }, { "CVR", typeof(ClientVersionCommand) }, { "USR", typeof(AuthenticateCommand) }, { "XFR", typeof(TransferCommand) }, { "SYN", typeof(SynchronizeCommand) }, { "SBS", typeof(SbsCommand) }, { "MSG", typeof(MessageCommand) }, { "LST", typeof(UserCommand) }, { "LSG", typeof(GroupCommand) }, { "BPR", typeof(UserPropertyCommand) }, { "BLP", typeof(PrivacySettingCommand) }, { "GTC", typeof(PrivacySettingCommand) }, { "CHG", typeof(ChangeStatusCommand) }, { "UBX", typeof(BroadcastCommand) }, { "PRP", typeof(LocalPropertyCommand) }, { "NLN", typeof(UserOnlineCommand) }, { "ILN", typeof(InitialUserOnlineCommand) }, { "FLN", typeof(UserOfflineCommand) }, { "UUX", typeof(SendBroadcastCommand) }, { "NOT", typeof(NotificationCommand) }, { "QNG", typeof(PingCommand) }, { "CHL", typeof(ChallengeCommand) }, { "ADC", typeof(AddContactCommand) }, { "REM", typeof(RemoveContactCommand) }, { "ADG", typeof(AddGroupCommand) }, { "RMG", typeof(RemoveGroupCommand) }, { "REG", typeof(RenameGroupCommand) }, { "QRY", typeof(AcceptChallengeCommand) }, { "RNG", typeof(RingCommand) }, { "SBP", typeof(ChangeUserPropertyCommand) }, { "IMS", typeof(EnableIMCommand) }, }); commands = reader.GetReadObservable().Publish(); responseTracker = new ResponseTracker(writer, commands); commandsDisposable = commands.Connect(); var versionCommand = new VersionCommand("MSNP12"); var versionResponse = await responseTracker.GetResponseAsync<VersionCommand>(versionCommand, defaultTimeout); if (versionResponse.Versions.Length == 0) throw new ProtocolNotAcceptedException(); var clientVersionCommand = new ClientVersionCommand { LocaleId = "0x0409", OsType = "winnt", OsVersion = "5.0", Architecture = "1386", LibraryName = "MSMSGS", ClientVersion = "5.0.0482", ClientName = "WindowsMessenger", LoginName = credentials.LoginName, }; await responseTracker.GetResponseAsync<ClientVersionCommand>(clientVersionCommand, defaultTimeout); var userCommand = new AuthenticateCommand("TWN", "I", credentials.LoginName); var userResponse = await responseTracker.GetResponseAsync(userCommand, new Type[] { typeof(AuthenticateCommand), typeof(TransferCommand) }, defaultTimeout); if (userResponse is AuthenticateCommand) { authTicket = (userResponse as AuthenticateCommand).Argument; } else if (userResponse is TransferCommand) { TransferCommand transferResponse = userResponse as TransferCommand; if (transferCount > 3) throw new InvalidOperationException("The maximum number of redirects has been reached."); transferCount++; endPoint = SocketEndPoint.Parse(transferResponse.Host); commandsDisposable.Dispose(); reader.Close(); writer.Close(); connection.Dispose(); } } PassportAuthentication auth = new PassportAuthentication(); string authToken = await auth.GetToken(credentials.LoginName, credentials.Password, authTicket); var authCommand = new AuthenticateCommand("TWN", "S", authToken); var authResponse = await responseTracker.GetResponseAsync<AuthenticateCommand>(authCommand, defaultTimeout); var synCommand = new SynchronizeCommand(syncTimeStamp1 ?? "0", syncTimeStamp2 ?? "0"); var synResponse = await responseTracker.GetResponseAsync<SynchronizeCommand>(synCommand, defaultTimeout); IDisposable syncCommandsSubscription = null; List<Command> syncCommands = null; if (synResponse.TimeStamp1 != syncTimeStamp1 || synResponse.TimeStamp2 != syncTimeStamp2) { syncCommands = new List<Command>(); Type[] syncTypes = new Type[] { typeof(MessageCommand), typeof(UserCommand), typeof(GroupCommand), typeof(LocalPropertyCommand), typeof(PrivacySettingCommand), }; syncCommandsSubscription = commands .Where(c => syncTypes.Contains(c.GetType())) .Catch(Observable.Empty<Command>()) .Subscribe(c => syncCommands.Add(c)); //if we're expecting users/groups, wait for them before we proceed if (synResponse.UserCount + synResponse.GroupCount > 0) { await commands .Where(c => c is UserCommand || c is GroupCommand) .Take(synResponse.UserCount + synResponse.GroupCount) .Timeout(defaultTimeout); } } UserCapabilities capabilities = 0; MSNObject displayPicture = MSNObject.Empty; if (LocalUser != null) { capabilities = LocalUser.Capabilities; displayPicture = LocalUser.DisplayPicture; } Command changeStatusCommand = new ChangeStatusCommand(User.StatusToString(UserStatus.Online), (uint)capabilities, displayPicture != MSNObject.Empty ? displayPicture.ToString() : "0"); await responseTracker.GetResponseAsync(changeStatusCommand, defaultTimeout); if (syncCommandsSubscription != null) syncCommandsSubscription.Dispose(); this.writer = writer; this.reader = reader; this.stream = stream; this.connection = connection; this.responseTracker = responseTracker; this.commands = commands; this.commandsDisposable = commandsDisposable; if (LocalUser == null) { LocalUser = new LocalUser(this, credentials.LoginName); userCache.Add(credentials.LoginName, new WeakReference(LocalUser)); } LocalUser.Status = initialStatus; SyncEvents syncEvents = null; if (syncCommands != null) { syncTimeStamp1 = synResponse.TimeStamp1; syncTimeStamp2 = synResponse.TimeStamp2; syncEvents = ProcessSyncCommands(syncCommands); } var commandsSafe = commands .Catch<Command, ConnectionErrorException>(tx => Observable.Empty<Command>()); commandsSafe.OfType<MessageCommand>().Subscribe(cmd => HandleMessages(cmd, connection)); commandsSafe.OfType<RingCommand>().Subscribe(cmd => HandleRings(cmd, connection)); commandsSafe.OfType<BroadcastCommand>().Subscribe(cmd => HandleBroadcasts(cmd, connection)); commandsSafe.OfType<NotificationCommand>().Subscribe(cmd => HandleNotifications(cmd, connection)); commandsSafe.OfType<AddContactCommand>().Subscribe(cmd => HandleNewUsers(cmd, connection)); commandsSafe.OfType<OutCommand>().Subscribe(cmd => HandleOut(cmd, connection)); commandsSafe.OfType<ChallengeCommand>().Subscribe(cmd => HandleChallenges(cmd, connection)); commandsSafe.OfType<UserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection)); commandsSafe.OfType<InitialUserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection)); commandsSafe.OfType<UserOfflineCommand>().Subscribe(cmd => HandleOfflineUsers(cmd, connection)); connection.Error += connection_Error; IsLoggedIn = true; OnLoggedIn(); OnUserStatusChanged(new UserStatusEventArgs(LocalUser, initialStatus, UserStatus.Offline, true)); if (syncEvents != null) RaiseSyncEvents(syncEvents); } finally { @lock.WriterRelease(); } }
private void SubscribeToQueryEvents() { var textChanged = this.textChangedObservable .Where(text => text != null && text.Length >= this.MinimumCharacters) .DistinctUntilChanged() .Throttle(TimeSpan.FromMilliseconds(this.Delay)); // Capture the function to avoid access to the dependency property on the subscriber thread. var getResultsFunc = this.AutoCompleteQueryResultProvider.GetResults; var resultsObservable = from searchTerm in textChanged from suggestions in getResultsFunc(new AutoCompleteQuery(searchTerm)).TakeUntil(textChanged) select suggestions; // Feed results into result list this.publishedResultsObservable = resultsObservable.Publish(); this.publishedResultsObservableConnection = this.publishedResultsObservable.Connect(); var publishedResultsObservableSubscription = this.publishedResultsObservable.Retry().ObserveOn(this).Subscribe( results => { IsBusy = false; this.Results.Clear(); foreach (var result in results) { this.Results.Add(result); } if (this.partListBox.SelectedItem == null) { this.partListBox.SelectedItem = this.Results.FirstOrDefault(); } if (this.partListBox.SelectedItem != null) { this.partListBox.ScrollIntoView(this.partListBox.SelectedItem); } }); this.subscriptions.Add(publishedResultsObservableSubscription); }
private void InitializeProcessing(IConnectableObservable<List<float>> channelObserver) { var interpolators = _config.Sensors.Select(s => new Interpolator.ChannelInterpolator(s.Interpolation)).ToList(); var interpolator = new Interpolator(interpolators); var platformSize = _config.Platform.Size; var leftPlatform = new PlatformDiagnostic(platformSize, _config.Sensors.Take(4).ToList(), _config.Platform.LeftCorrection); var rightPlatform = new PlatformDiagnostic(platformSize, _config.Sensors.Skip(4).ToList(), _config.Platform.RightCorrection); var filtered = CurrentAvfFilter.Filter(channelObserver, 10); var weightObserver = interpolator.Interpolate(filtered); var leftWeightObserver = weightObserver.Select(list => list.Take(4).ToList()); var rightWeightObserver = weightObserver.Select(list => list.Skip(4).ToList()); var leftCenterObserver = leftPlatform.Center(leftWeightObserver); var rightCenterObserver = rightPlatform.Center(rightWeightObserver); _indicatorsForm.Prepare(leftPlatform, leftCenterObserver, rightPlatform, rightCenterObserver); var plotDataObserver = leftCenterObserver.ObserveOn(Scheduler.Default).Zip(rightCenterObserver, (l, r) => new PlotData() {LeftPoint = l, RightPoint = r}); StartTracking(plotDataObserver); }
KanColleGame() { Proxy = new GameProxy(); Headquarter = new Headquarter(); QuestTable = new Table<Quest>(); Fleets = new Table<Fleet>(); Ships = new Table<Ship>(); Equipments = new Table<Equipment>(); ObservablePropertyChanged = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>( rpHandler => PropertyChanged += rpHandler, rpHandler => PropertyChanged -= rpHandler) .Select(r => r.EventArgs.PropertyName) .Publish(); r_PropertyChangedSubscriptions = ObservablePropertyChanged.Connect(); }
void Awake() { //60秒カウントのストリームを作成 //PublishでHot変換 _countDownObservable = CreateCountDownObservable(15).Publish(); }
static TimerNotifier() { timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1)).Publish(); timer.Connect(); }