public MainWindowViewModel() { var noneInFlight = new BehaviorSubject <bool>(false); var updateManager = default(UpdateManager); this.WhenAny(x => x.UpdatePath, x => x.Value) .Where(x => !String.IsNullOrWhiteSpace(x)) .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler) .Subscribe(x => { if (updateManager != null) { updateManager.Dispose(); } updateManager = new UpdateManager(UpdatePath, "SampleUpdatingApp", FrameworkVersion.Net40); }); CheckForUpdate = new ReactiveAsyncCommand(noneInFlight); CheckForUpdate.RegisterAsyncObservable(_ => updateManager.CheckForUpdate()) .Subscribe(x => { UpdateInfo = x; DownloadedUpdateInfo = null; }); DownloadReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => UpdateInfo != null)); DownloadReleases.RegisterAsyncObservable(_ => updateManager.DownloadReleases(UpdateInfo.ReleasesToApply)) .Subscribe(_ => DownloadedUpdateInfo = UpdateInfo); ApplyReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => DownloadedUpdateInfo != null)); ApplyReleases.RegisterAsyncObservable(_ => updateManager.ApplyReleases(DownloadedUpdateInfo)); Observable.CombineLatest( CheckForUpdate.ItemsInflight.StartWith(0), DownloadReleases.ItemsInflight.StartWith(0), ApplyReleases.ItemsInflight.StartWith(0), this.WhenAny(x => x.UpdatePath, _ => 0), (a, b, c, _) => a + b + c ).Select(x => x == 0 && UpdatePath != null).Multicast(noneInFlight).Connect(); }
public MainWindowViewModel() { var noneInFlight = new BehaviorSubject<bool>(false); var updateManager = default(UpdateManager); this.WhenAny(x => x.UpdatePath, x => x.Value) .Where(x => !String.IsNullOrWhiteSpace(x)) .Throttle(TimeSpan.FromMilliseconds(700), RxApp.DeferredScheduler) .Subscribe(x => { if (updateManager != null) updateManager.Dispose(); updateManager = new UpdateManager(UpdatePath, "SampleUpdatingApp", FrameworkVersion.Net40); }); CheckForUpdate = new ReactiveAsyncCommand(noneInFlight); CheckForUpdate.RegisterAsyncObservable(_ => updateManager.CheckForUpdate()) .Subscribe(x => { UpdateInfo = x; DownloadedUpdateInfo = null; }); DownloadReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => UpdateInfo != null)); DownloadReleases.RegisterAsyncObservable(_ => updateManager.DownloadReleases(UpdateInfo.ReleasesToApply)) .Subscribe(_ => DownloadedUpdateInfo = UpdateInfo); ApplyReleases = new ReactiveAsyncCommand(noneInFlight.Where(_ => DownloadedUpdateInfo != null)); ApplyReleases.RegisterAsyncObservable(_ => updateManager.ApplyReleases(DownloadedUpdateInfo)); Observable.CombineLatest( CheckForUpdate.ItemsInflight.StartWith(0), DownloadReleases.ItemsInflight.StartWith(0), ApplyReleases.ItemsInflight.StartWith(0), this.WhenAny(x => x.UpdatePath, _ => 0), (a, b, c, _) => a + b + c ).Select(x => x == 0 && UpdatePath != null).Multicast(noneInFlight).Connect(); }
/// <summary> /// window function and scheduler for testing. /// </summary> /// <returns></returns> private static async Task test2() { var scheduler = new TestScheduler(); var bandStatus = new BehaviorSubject <Status>(Status.Disconnected); var closingWindowCondition = bandStatus.Where(i => i != Status.Disconnected).DistinctUntilChanged(); var openingWindowCondition = bandStatus.Where(i => i == Status.Disconnected).DistinctUntilChanged(); var condition = bandStatus.Window(openingWindowCondition, _ => closingWindowCondition); var idx = 0; var initialdt = scheduler.Now; var signalingSub = new Subject <Unit>(); condition .ObserveOn(scheduler) .Subscribe(w => { initialdt = scheduler.Now; Console.WriteLine($"Window {idx++} is here"); w.Subscribe(_ => { }, () => { Console.WriteLine($">>>>> Window {idx} closing"); if (scheduler.Now - initialdt > TimeSpan.FromSeconds(3)) { signalingSub.OnNext(Unit.Default); } }); }); ///How to use DateTime with TestSchedular? : IScheduler.Now signalingSub.Subscribe(_ => Console.WriteLine(">>>>>>> valid disconnection happened <<<<<<<")); //behavior: when connected, and if there has been x amount of time in disconnection, tick. //Even though the tighter condition would be that //if more than x sec has passed in disconnected state, this subject should tick already. //It doesn't make sense with Disconnected since we're upgrading. //so this behavior is ok. Console.WriteLine("first disconnected to open the window"); bandStatus.OnNext(Status.Disconnected); scheduler.AdvanceBy(TimeSpan.FromSeconds(4).Ticks); Console.WriteLine("4 sec delay in Disconnected state, then Connected, done. Now it's valid time."); bandStatus.OnNext(Status.Connected); Console.WriteLine("===============\nnow Connected"); Console.WriteLine("rest 1 sec"); scheduler.AdvanceBy(TimeSpan.FromSeconds(1).Ticks); bandStatus.OnNext(Status.Disconnected); scheduler.AdvanceBy(TimeSpan.FromSeconds(2).Ticks); bandStatus.OnNext(Status.Connected); Console.WriteLine("2 sec of disconnection happened. No tick should happen."); }
private async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) #endif { await dataAvailable.Where(b => b).Take(1); return(Read(buffer, offset, count)); }
private void InitiateAddingItemsToDB() { _dispose?.Dispose(); _dispose = null; waitSub?.Dispose(); waitSub = null; _dispose = new BehaviorSubject <bool>(true); var currentSliderSpeed = ((ThoughtEntryVM)this.BindingContext).Speed; var adjustedSpeed = currentSliderSpeed * 2; waitSub?.Dispose(); if (Convert.ToInt32(currentSliderSpeed) != 100 && Convert.ToInt32(currentSliderSpeed) != 0) { waitSub = Observable .Interval(TimeSpan.FromMilliseconds(adjustedSpeed)) .TakeUntil(_dispose.Where(p => !p)) //.Take(1) .Subscribe(val => { if (jsonString == null) { jsonString = JsonConvert.SerializeObject(new List <string>() { "Me", "You", "Us" }); } var newobj = JsonConvert.DeserializeObject(jsonString); ((ThoughtEntryVM)this.BindingContext).AutoThought = JsonConvert.SerializeObject(newobj); ((ThoughtEntryVM)this.BindingContext).AutoGetNumberOfRows = true; ((ThoughtEntryVM)this.BindingContext).AutoGetDBSize = true; }); } }
protected override void Main() { if (Environment.OSVersion.Version < new Version(6, 2)) { TraceError(Text.LabRequiresWindows8OrHigher); return; } const int port = 5494; string subProtocol = GetType().Name; var userMessages = new BehaviorSubject <string>(null); var client = new ClientWebSocket(); client.Options.AddSubProtocol(subProtocol); using (client) using (var cancel = new CancellationDisposable()) using (ObservableHttpListener .StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol) .Subscribe( async request => { using (var socket = request.WebSocket) { try { var message = await ReceiveMessageAsync(socket, cancel.Token); await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token); await ReceiveCloseMessageAsync(socket, cancel.Token); } catch (OperationCanceledException) { } } }, TraceError)) using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable() .Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol)) from message in userMessages.Where(m => m != null).Take(1) from __ in SendMessageAsync(message, client, cancel.Token).ToObservable() from response in ReceiveMessageAsync(client, cancel.Token).ToObservable() .Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token)) select response) .Subscribe( response => TraceLine("Response: {0}", response), TraceError, () => TraceLine("{0}: {1}", Text.Client, Text.Done))) { userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage)); TraceStatus(Instructions.PressAnyKeyToCancel); WaitForKey(); } }
protected override void Main() { if (Environment.OSVersion.Version < new Version(6, 2)) { TraceError(Text.LabRequiresWindows8OrHigher); return; } const int port = 5494; string subProtocol = GetType().Name; var userMessages = new BehaviorSubject<string>(null); var client = new ClientWebSocket(); client.Options.AddSubProtocol(subProtocol); using (client) using (var cancel = new CancellationDisposable()) using (ObservableHttpListener .StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol) .Subscribe( async request => { using (var socket = request.WebSocket) { try { var message = await ReceiveMessageAsync(socket, cancel.Token); await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token); await ReceiveCloseMessageAsync(socket, cancel.Token); } catch (OperationCanceledException) { } } }, TraceError)) using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable() .Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol)) from message in userMessages.Where(m => m != null).Take(1) from __ in SendMessageAsync(message, client, cancel.Token).ToObservable() from response in ReceiveMessageAsync(client, cancel.Token).ToObservable() .Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token)) select response) .Subscribe( response => TraceLine("Response: {0}", response), TraceError, () => TraceLine("{0}: {1}", Text.Client, Text.Done))) { userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage)); TraceStatus(Instructions.PressAnyKeyToCancel); WaitForKey(); } }
internal async Task <Response> SendCommandAsyncInternal(Command command) { await _comm.WriteAsync(command.ToBytes()); return(command.CommandType == CommandType.DirectReply || command.CommandType == CommandType.SystemReply ? await _subject .Where(r => r != null && r.Sequence == command.SequenceNumber) .FirstAsync() : null); }
public ServiceHostEventListener(IQueryDispatcher queryDispatcher, IOptions <ServiceHostEventListenerOptions>?options, ILogger <ServiceHostEventListener>?logger) { _queryDispatcher = queryDispatcher ?? throw new ArgumentNullException(nameof(queryDispatcher)); _logger = logger ?? (ILogger)NullLogger.Instance; var optionsValue = options?.Value; _delayOnDropout = optionsValue?.DelayOnDropout ?? ServiceHostEventListenerOptions.DefaultDelayOnDropout; _isActiveSubject = new BehaviorSubject <bool>(true); IsActive = _isActiveSubject .StartWith(true) .DistinctUntilChanged(); var events = Observable .Create <Event>(observer => { var query = new StreamBusEventsQuery { OnEvent = (_, @event) => observer.OnNext(@event) }; return(Observable .FromAsync(async ct => { await _queryDispatcher.DispatchAsync(query, ct).ConfigureAwait(false); throw new InvalidOperationException($"{nameof(StreamBusEventsQuery)} returned unexpectedly."); }) .Subscribe(Noop <Unit> .Action, observer.OnError)); }) .Do(OnEventReceived, OnStreamError) .Retry(wrapSubsequent: source => source.DelaySubscription(_delayOnDropout)) // when subject completes, event stream should complete as well .TakeUntil(_isActiveSubject.Where(_ => false).Materialize()) .Publish(); _events = events.AsObservable(); // no need to explicitly disconnect in Dispose because of TakeUntil events.Connect(); }
static void Main(string[] args) { var subject = new BehaviorSubject <ConnectionState>(ConnectionState.Disconnected); var getCredentials = subject.Where(cs => cs == ConnectionState.RequiresCredentials) .Select(cs => { Console.WriteLine("Enter username"); var userName = Console.ReadLine(); Console.WriteLine("Enter password"); var password = Console.ReadLine(); return(Tuple.Create(userName, password)); }); using (var subscription = getCredentials.Subscribe()) { Console.WriteLine("Changing to Connecting..."); subject.OnNext(ConnectionState.Connecting); Console.WriteLine("Changing to RequiresCredentials..."); subject.OnNext(ConnectionState.RequiresCredentials); Console.WriteLine("Connected."); subject.OnNext(ConnectionState.Connected); } }
public EditTimeEntryViewModel( ITimeService timeService, ITogglDataSource dataSource, ISyncManager syncManager, IInteractorFactory interactorFactory, INavigationService navigationService, IOnboardingStorage onboardingStorage, IAnalyticsService analyticsService, IRxActionFactory actionFactory, ISchedulerProvider schedulerProvider) : base(navigationService) { Ensure.Argument.IsNotNull(dataSource, nameof(dataSource)); Ensure.Argument.IsNotNull(syncManager, nameof(syncManager)); Ensure.Argument.IsNotNull(timeService, nameof(timeService)); Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory)); Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage)); Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService)); Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider)); Ensure.Argument.IsNotNull(actionFactory, nameof(actionFactory)); this.dataSource = dataSource; this.syncManager = syncManager; this.timeService = timeService; this.interactorFactory = interactorFactory; this.analyticsService = analyticsService; this.schedulerProvider = schedulerProvider; this.actionFactory = actionFactory; OnboardingStorage = onboardingStorage; workspaceIdSubject .Where(id => id.HasValue) .Subscribe(id => workspaceId = id.Value) .DisposedBy(disposeBag); isEditingDescriptionSubject = new BehaviorSubject <bool>(false); Description = new BehaviorRelay <string>(string.Empty, CommonFunctions.Trim); projectClientTaskSubject = new BehaviorSubject <ProjectClientTaskInfo>(ProjectClientTaskInfo.Empty); ProjectClientTask = projectClientTaskSubject .AsDriver(ProjectClientTaskInfo.Empty, schedulerProvider); IsBillableAvailable = workspaceIdSubject .Where(id => id.HasValue) .SelectMany(workspaceId => interactorFactory.IsBillableAvailableForWorkspace(workspaceId.Value).Execute()) .DistinctUntilChanged() .AsDriver(false, schedulerProvider); isBillableSubject = new BehaviorSubject <bool>(false); IsBillable = isBillableSubject .DistinctUntilChanged() .AsDriver(false, schedulerProvider); startTimeSubject = new BehaviorSubject <DateTimeOffset>(DateTimeOffset.UtcNow); var startTimeObservable = startTimeSubject.DistinctUntilChanged(); StartTime = startTimeObservable .AsDriver(default(DateTimeOffset), schedulerProvider); var now = timeService.CurrentDateTimeObservable.StartWith(timeService.CurrentDateTime); durationSubject = new ReplaySubject <TimeSpan?>(bufferSize: 1); Duration = durationSubject .Select(duration => duration.HasValue ? Observable.Return(duration.Value) : now.CombineLatest( startTimeObservable, (currentTime, startTime) => currentTime - startTime)) .Switch() .DistinctUntilChanged() .AsDriver(TimeSpan.Zero, schedulerProvider); var stopTimeObservable = Observable.CombineLatest(startTimeObservable, durationSubject, calculateStopTime) .DistinctUntilChanged(); StopTime = stopTimeObservable .AsDriver(null, schedulerProvider); var isTimeEntryRunningObservable = stopTimeObservable .Select(stopTime => !stopTime.HasValue) .Do(value => isRunning = value) .DistinctUntilChanged(); IsTimeEntryRunning = isTimeEntryRunningObservable .AsDriver(false, schedulerProvider); tagsSubject = new BehaviorSubject <IEnumerable <IThreadSafeTag> >(Enumerable.Empty <IThreadSafeTag>()); Tags = tagsSubject .Select(tags => tags.Select(ellipsize).ToImmutableList()) .AsDriver(ImmutableList <string> .Empty, schedulerProvider); isInaccessibleSubject = new BehaviorSubject <bool>(false); IsInaccessible = isInaccessibleSubject .DistinctUntilChanged() .AsDriver(false, schedulerProvider); syncErrorMessageSubject = new BehaviorSubject <string>(string.Empty); SyncErrorMessage = syncErrorMessageSubject .Select(error => error ?? string.Empty) .DistinctUntilChanged() .AsDriver(string.Empty, schedulerProvider); IsSyncErrorMessageVisible = syncErrorMessageSubject .Select(error => !string.IsNullOrEmpty(error)) .DistinctUntilChanged() .AsDriver(false, schedulerProvider); Preferences = interactorFactory.GetPreferences().Execute() .AsDriver(null, schedulerProvider); // Actions SelectProject = actionFactory.FromAsync(selectProject); SelectTags = actionFactory.FromAsync(selectTags); ToggleBillable = actionFactory.FromAction(toggleBillable); EditTimes = actionFactory.FromAsync <EditViewTapSource>(editTimes); SelectStartDate = actionFactory.FromAsync(selectStartDate); StopTimeEntry = actionFactory.FromAction(stopTimeEntry, isTimeEntryRunningObservable); DismissSyncErrorMessage = actionFactory.FromAction(dismissSyncErrorMessage); Save = actionFactory.FromAsync(save); Delete = actionFactory.FromAsync(delete); }
public IObservable <DataDimension> GetDimension(string column) { return(_isInitialized.Where(x => x).First().Select(_ => _dimensions.FirstOrDefault(d => d.Column == column))); }
public EditDurationViewModel(INavigationService navigationService, ITimeService timeService, ITogglDataSource dataSource, IAnalyticsService analyticsService, IRxActionFactory rxActionFactory, ISchedulerProvider schedulerProvider) : base(navigationService) { Ensure.Argument.IsNotNull(timeService, nameof(timeService)); Ensure.Argument.IsNotNull(dataSource, nameof(dataSource)); Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService)); Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory)); Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider)); this.timeService = timeService; this.analyticsService = analyticsService; this.dataSource = dataSource; Save = rxActionFactory.FromAction(save); EditStartTime = rxActionFactory.FromAction(editStartTime); EditStopTime = rxActionFactory.FromAction(editStopTime); StopEditingTime = rxActionFactory.FromAction(stopEditingTime); ChangeStartTime = rxActionFactory.FromAction <DateTimeOffset>(updateStartTime); ChangeStopTime = rxActionFactory.FromAction <DateTimeOffset>(updateStopTime); ChangeActiveTime = rxActionFactory.FromAction <DateTimeOffset>(changeActiveTime); ChangeDuration = rxActionFactory.FromAction <TimeSpan>(changeDuration); StopTimeEntry = rxActionFactory.FromAction(stopTimeEntry); var start = startTime.Where(v => v != default(DateTimeOffset)); var stop = stopTime.Where(v => v != default(DateTimeOffset)); var duration = Observable.CombineLatest(start, stop, (startValue, stopValue) => stopValue - startValue); StartTime = start.AsDriver(schedulerProvider); StopTime = stop.AsDriver(schedulerProvider); Duration = duration.AsDriver(schedulerProvider); IsEditingTime = editMode.Select(v => v != EditMode.None).AsDriver(schedulerProvider); IsEditingStartTime = editMode.Select(v => v == EditMode.StartTime).AsDriver(schedulerProvider); IsEditingStopTime = editMode.Select(v => v == EditMode.EndTime).AsDriver(schedulerProvider); var preferences = dataSource.Preferences.Current.ShareReplay(); var dateFormat = preferences.Select(p => p.DateFormat); var timeFormat = preferences.Select(p => p.TimeOfDayFormat); var durationFormat = preferences.Select(p => p.DurationFormat); StartDateString = Observable.CombineLatest(start, dateFormat, toFormattedString) .AsDriver(schedulerProvider); StartTimeString = Observable.CombineLatest(start, timeFormat, toFormattedString) .AsDriver(schedulerProvider); StopDateString = Observable.CombineLatest(stop, dateFormat, toFormattedString) .AsDriver(schedulerProvider); StopTimeString = Observable.CombineLatest(stop, timeFormat, toFormattedString) .AsDriver(schedulerProvider); DurationString = Observable.CombineLatest(duration, durationFormat, toFormattedString) .AsDriver(schedulerProvider); TimeFormat = timeFormat.AsDriver(schedulerProvider); IsRunning = isRunning.AsDriver(schedulerProvider); MinimumDateTime = minimumDateTime.AsDriver(schedulerProvider); MaximumDateTime = maximumDateTime.AsDriver(schedulerProvider); MinimumStartTime = stopTime.Select(v => v.AddHours(-MaxTimeEntryDurationInHours)).AsDriver(schedulerProvider); MaximumStartTime = stopTime.AsDriver(schedulerProvider); MinimumStopTime = startTime.AsDriver(schedulerProvider); MaximumStopTime = startTime.Select(v => v.AddHours(MaxTimeEntryDurationInHours)).AsDriver(schedulerProvider); }
public ReportsViewModel(ITogglDataSource dataSource, ITimeService timeService, INavigationService navigationService, IInteractorFactory interactorFactory, IAnalyticsService analyticsService, ISchedulerProvider schedulerProvider, IRxActionFactory rxActionFactory) : base(navigationService) { Ensure.Argument.IsNotNull(dataSource, nameof(dataSource)); Ensure.Argument.IsNotNull(timeService, nameof(timeService)); Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory)); Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService)); Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory)); Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider)); Ensure.Argument.IsNotNull(navigationService, nameof(navigationService)); this.dataSource = dataSource; this.timeService = timeService; this.analyticsService = analyticsService; this.interactorFactory = interactorFactory; CalendarViewModel = new ReportsCalendarViewModel(timeService, dataSource, rxActionFactory, navigationService); var totalsObservable = reportSubject .SelectMany(_ => interactorFactory.GetReportsTotals(userId, workspaceId, startDate, endDate).Execute()) .Catch <ITimeEntriesTotals, OfflineException>(_ => Observable.Return <ITimeEntriesTotals>(null)) .Where(report => report != null); BarChartViewModel = new ReportsBarChartViewModel(schedulerProvider, dataSource.Preferences, totalsObservable, navigationService); IsLoadingObservable = isLoading.AsObservable().StartWith(true).AsDriver(schedulerProvider); StartDate = startDateSubject.AsObservable().AsDriver(schedulerProvider); EndDate = endDateSubject.AsObservable().AsDriver(schedulerProvider); SelectWorkspace = rxActionFactory.FromAsync(selectWorkspace); WorkspaceNameObservable = workspaceSubject .Select(workspace => workspace?.Name ?? string.Empty) .DistinctUntilChanged() .AsDriver(schedulerProvider); WorkspaceHasBillableFeatureEnabled = workspaceSubject .Where(workspace => workspace != null) .SelectMany(workspace => interactorFactory.GetWorkspaceFeaturesById(workspace.Id).Execute()) .Select(workspaceFeatures => workspaceFeatures.IsEnabled(WorkspaceFeatureId.Pro)) .StartWith(false) .DistinctUntilChanged() .AsDriver(schedulerProvider); CurrentDateRange = currentDateRangeStringSubject .Select(text => !string.IsNullOrEmpty(text) ? $"{text} ▾" : "") .DistinctUntilChanged() .AsDriver(schedulerProvider); WorkspacesObservable = interactorFactory.ObserveAllWorkspaces().Execute() .Select(list => list.Where(w => !w.IsInaccessible)) .Select(readOnlyWorkspaceSelectOptions) .AsDriver(schedulerProvider); DurationFormatObservable = dataSource.Preferences.Current .Select(prefs => prefs.DurationFormat) .AsDriver(schedulerProvider); SegmentsObservable = segmentsSubject.CombineLatest(DurationFormatObservable, applyDurationFormat); GroupedSegmentsObservable = SegmentsObservable.CombineLatest(DurationFormatObservable, groupSegments); ShowEmptyStateObservable = SegmentsObservable.CombineLatest(IsLoadingObservable, shouldShowEmptyState); }
protected override Task RunInternal() { _observeCacheState = _state .Where(state => state == DynamicCacheState.Reconnected) .Subscribe((state) => { _isCaughtingUp = true; _sourceCache.Edit((updater) => { updater.Clear(); var stateOfTheWorld = GetStateOfTheWorld(); var update = new Action <IEvent <TKey, TAggregate> >((@event) => { var aggregate = updater.Lookup(@event.EventStreamId); if (!aggregate.HasValue) { var @new = new TAggregate { Id = @event.EventStreamId }; @new.Apply(@event); updater.AddOrUpdate(@new); } else { aggregate.Value.Apply(@event); updater.AddOrUpdate(aggregate.Value); } }); foreach (var eventMessage in stateOfTheWorld.Events) { var @event = _eventSerializer.ToEvent <TKey, TAggregate>(eventMessage); update(@event); } lock (_caughtingUpLock) { var replayEvents = _caughtingUpCache.CaughtUpEvents .Where(ev => !stateOfTheWorld.Events.Any(msg => msg.EventId.Id == ev.EventId)) .ToList(); foreach (var @event in replayEvents) { update(@event); } } }); _isCaughtingUp = false; _caughtingUpCache.Clear(); }); _workProc = Task.Run(HandleWork, _cancel.Token).ConfigureAwait(false); _heartbeatProc = Task.Run(HandleHeartbeat, _cancel.Token).ConfigureAwait(false); return(Task.CompletedTask); }
public DynamicCache(IDynamicCacheConfiguration configuration, ILogger <DynamicCache <TKey, TAggregate> > logger, IEventSerializer eventSerializer) : base(logger) { _blockEventConsumption = new ManualResetEventSlim(true); _cacheErrors = new ObservableCollection <ActorMonitoringError>(); _logger = logger; _cleanup = new CompositeDisposable(); _eventSerializer = eventSerializer; _configuration = configuration; _sourceCache = new SourceCache <TAggregate, TKey>(selector => selector.Id); _cancel = new CancellationTokenSource(); _state = new BehaviorSubject <DynamicCacheState>(DynamicCacheState.NotConnected); _isStaled = new BehaviorSubject <bool>(true); _isCaughtingUp = new BehaviorSubject <bool>(false); _caughtingUpCache = new CaughtingUpCache <TKey, TAggregate>(); _getStateOfTheWorldRetyPolicy = Policy.Handle <Exception>() .RetryForever((ex) => { _cacheErrors.Add(new ActorMonitoringError() { CacheErrorStatus = ActorErrorType.DynamicCacheGetStateOfTheWorldFailure, Exception = ex }); }); //on reconnected start try to caught up _state.Subscribe(state => { _logger.LogInformation($"Cache state is {state}"); if (state == DynamicCacheState.Reconnected) { _isCaughtingUp.OnNext(true); } }).Cleanup(_cleanup); //start caughting up by fetching the broker state of the world _isCaughtingUp .Where(state => state) .Subscribe(_ => _caughtUpWithStateOfTheWorldProc = Task.Run(() => { WaitUntilConnected(); WaitUntilCaughtUpToStateOfTheWorld(); }, _cancel.Token)) .Cleanup(_cleanup); Observable.FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs> (e => Errors.CollectionChanged += e, e => Errors.CollectionChanged -= e) .Where(arg => arg.EventArgs.NewItems.Count > 0) .Subscribe(arg => { foreach (var error in arg.EventArgs.NewItems.Cast <ActorMonitoringError>()) { _logger.LogError(error.Message, error.Exception); } }) .Cleanup(_cleanup); }
private IDisposable ShouldSetDataContextWhenViewAttached() { return(_view .Where(view => view != null) .Subscribe(view => view.DataContext = this)); }
/// <summary> /// トリガーにかかるか例外が出るまで待つ /// </summary> /// <param name="bs"></param> /// <param name="trigger"></param> /// <param name="status"></param> /// <returns></returns> private async Task WaitTriggerAsync(BehaviorSubject<bool> bs, IDisposable trigger, StatusItem status) { await this.SendLineAsync(null); this.StatusSubject.OnNext(status); var waiting = await bs .Where(x => x) .Select(x => new WaitResultContainer(null)) .Merge(this.ExceptionObservable) .Take(1); trigger.Dispose(); bs.Dispose(); if (!waiting.IsSucceeded) { throw waiting.Exception; } await this.WaitIfPausingAsync(); }