public static IDisposable GetValueAndSubscribe <T>(this IReadOnlyReactiveProperty <T> source, IObserver <T> observer) { var disposable = source.Subscribe(observer); observer.OnNext(source.Value); return(disposable); }
public LogicNode(ILogicNode parentNode, string name) { Parent = parentNode; Name = name; _completeFactor = _ownFactor.CombineLatest(parentNode.CompleteFactor, (own, parent) => own * parent).ToReactiveProperty(); }
public Player() { BaseStats = new Stats(100, 100, 100); Armor = new ReactiveProperty <Item>(); Weapon = new ReactiveProperty <Item>(); Shield = new ReactiveProperty <Item>(); Accessory = new ReactiveProperty <Item>(); Inventory = new ReactiveCollection <Item>(); InventoryWeight = Observable.Merge(new[] { AllItemSlots.Merge().Select(_ => new Unit()), Inventory.ObserveCountChanged().Select(_ => new Unit()), }) .StartWith(new Unit()) .Select(_ => Inventory .Concat(AllItemSlots.Where(SlotHasItemEquipped).Select(x => x.Value)) .Aggregate(0, (collector, next) => collector + next.Weight) ) .ToReadOnlyReactiveProperty(); Stats = AllItemSlots .Merge() .CombineLatest(InventoryWeight, Tuple.Create) .Select(x => { var invWeight = x.Item2; var allWeight = GameDataManager.instance.AllItemsWeight; var modifiedStats = BaseStats + EquippedItemModifiers(); var weightBurden = GameDataManager.instance.GetPlayerTunedWeightBurden(invWeight); var finalStats = new Stats(modifiedStats.Hp, modifiedStats.Mp, modifiedStats.Speed * (1 - weightBurden)); Debug.Log($"Update stats, modified:{modifiedStats} invWeight:{invWeight} allWeight:{allWeight} normalWeight:{invWeight / (float)allWeight} weightBurden:{weightBurden} finalStats:{finalStats}"); return(finalStats); }) .ToReadOnlyReactiveProperty(); }
public DownloadStatus() { Bytes = new ReactiveProperty <long>(); TotalBytes = new ReactiveProperty <long>(); Progress = Bytes.CombineLatest(TotalBytes, (b, t) => t > 0 ? (double)b / (double)t : 0.0) .ToReadOnlyReactiveProperty(); Weight = new ReactiveProperty <double>(); IsActive = new ReactiveProperty <bool>(); Description = new ReactiveProperty <string>(); IsIdle = new ReactiveProperty <bool>(); IsActive.Subscribe(_ => { _downloadSpeedCalculator.Restart(DateTime.Now); }); var timedBytes = Bytes.Select(b => new ByteSample { Bytes = b, Timestamp = DateTime.Now }); var interval = Observable .Interval(TimeSpan.FromSeconds(1)) .Select(_ => new ByteSample { Bytes = Bytes.Value, Timestamp = DateTime.Now }); var updateStream = timedBytes.Merge(interval); BytesPerSecond = updateStream .Select(b => _downloadSpeedCalculator.Calculate(b.Bytes, b.Timestamp)) .ToReadOnlyReactiveProperty(); }
protected void Start() { m_text = GetComponent <Text>(); IReadOnlyReactiveProperty <int> property = GetProperty <int>(); property.TakeUntilDestroy(this).SubscribeToText(m_text).AddTo(this); }
public MobileARSupportProvider() { var currentARSessionState = Observable .FromEvent <ARSessionStateChangedEventArgs>( h => ARSession.stateChanged += h, h => ARSession.stateChanged -= h) .Select(args => args.state) .ToReadOnlyReactiveProperty(ARSession.state); ARIsCheckedAndSupported = currentARSessionState .Select(state => !(state == ARSessionState.None || state == ARSessionState.CheckingAvailability || state == ARSessionState.Unsupported)) .ToReadOnlyReactiveProperty(); ARIsReady = currentARSessionState .Select(state => state == ARSessionState.Ready || state == ARSessionState.SessionInitializing || state == ARSessionState.SessionTracking) .ToReadOnlyReactiveProperty(); NeedInstall = currentARSessionState .Select(state => state == ARSessionState.NeedsInstall) .ToReadOnlyReactiveProperty(); IsInstalling = currentARSessionState .Select(state => state == ARSessionState.Installing) .ToReadOnlyReactiveProperty(); AddDisposable(currentARSessionState); CoroutineRunner.Run(CheckAvailability()); }
public override void AlwaysStart() { IReadOnlyReactiveProperty <int> property = GetProperty <int>(); (from val in property.TakeWhile((int _) => this != null) select ShouldBeActive(val)).SubscribeToActiveUntilNull(base.gameObject).AddTo(this); }
public TwoWay2ViewModel() { // ignoreValidationErrorValue=true なら検証エラー時、Model に値を書き込まない InputInt2 = _model.ToReactivePropertyAsSynchronized( x => x.UserInt2, convert: m => m.ToString(), convertBack: vm => int.Parse(vm), ignoreValidationErrorValue: true) .SetValidateAttribute(() => InputInt2) .AddTo(CompositeDisposable); InputDouble2 = _model.ToReactivePropertyAsSynchronized( x => x.UserDouble2, convert: m => m.ToString(), convertBack: vm => double.Parse(vm), ignoreValidationErrorValue: true) .SetValidateAttribute(() => InputDouble2) .AddTo(CompositeDisposable); // 以下、確認用にModelの値を別口で参照 CheckModelValueInt2 = _model.ObserveProperty(x => x.UserInt2) .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); CheckModelValueDouble2 = _model.ObserveProperty(x => x.UserDouble2) .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); }
public BottleDetectionUseCases(CompositeDisposable disposables) : base(disposables) { photoCamera = new PhotoCamera(); client = new CustomVisionClient(); CanTakePhoto = Observable.CombineLatest(photoCamera.CanTakePhoto, client.CanPost) .Select(x => !x.Contains(false)) .ToReactiveProperty(); PhotoCamera.ShootingPlan plan = null; byte[] imageData = null; photoCamera.OnPhotoCaptured .Do(b => { plan = photoCamera.Plan; imageData = b; }) .SelectMany(x => client.Post(x)) .Do(res => { var positions = client.Convert(plan, imageData, res); var status = new DetectedStatus { Plan = plan, Positions = positions, }; onBottleDetected.OnNext(status); }) .Subscribe() .AddTo(disposables); }
public SelectFixRectViewModel() { MouseLeftDownPoint = new ReactivePropertySlim <RoixBorderPoint>(mode: ReactivePropertyMode.None); MouseMovePoint = new ReactivePropertySlim <RoixBorderPoint>(); ViewBorderSize = new ReactivePropertySlim <RoixSize>(mode: ReactivePropertyMode.DistinctUntilChanged); var imageSourceSize = MyImage.ToRoixIntSize(); // 画像座標系の固定サイズ枠(これを基準に管理する) 右クリックで固定サイズの枠を描画する var clickedFixedRectangleOnImage = MouseLeftDownPoint .Where(border => border.Border.IsNotZero) .Select(borderPointOnView => { var length = 100; var rectBorderSize = new RoixIntSize(length).ToRoixBorder(imageSourceSize); var rectHalfSize = rectBorderSize.Size / 2d; var newCenterPoint = borderPointOnView.ConvertToNewBorderInt(imageSourceSize); var newRect = new RoixBorderIntRect(newCenterPoint - (RoixIntVector)rectHalfSize, rectBorderSize); return(newRect.GetClippedBorderIntRect(isPointPriority: false)); }) .ToReadOnlyReactivePropertySlim(); // Model通知 ClickedFixedRectangleToModel = clickedFixedRectangleOnImage .Where(border => border.Border.IsNotZero) .Select(borderRectOnView => borderRectOnView.Roi) .ToReadOnlyReactivePropertySlim(); // View座標系の選択枠 ClickedFixedRectangle = clickedFixedRectangleOnImage .CombineLatest(ViewBorderSize, (rect, border) => rect.ConvertToNewBorder(border).Roi) .ToReadOnlyReactivePropertySlim(); }
public int Serialize(ref byte[] bytes, int offset, IReadOnlyReactiveProperty <T> value, IFormatterResolver formatterResolver) { var rxProp = value as ReactiveProperty <T>; if (rxProp != null) { return(ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactiveProperty <T> >().Serialize(ref bytes, offset, rxProp, formatterResolver)); } var slimProp = value as ReactivePropertySlim <T>; if (slimProp != null) { return(ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactivePropertySlim <T> >().Serialize(ref bytes, offset, slimProp, formatterResolver)); } if (value == null) { return(MessagePackBinary.WriteNil(ref bytes, offset)); } else { throw new InvalidOperationException("Serializer only supports ReactiveProperty<T> or ReactivePropertySlim<T>. If serialize is ReadOnlyReactiveProperty, should mark [Ignore] and restore on IMessagePackSerializationCallbackReceiver.OnAfterDeserialize. Type:" + value.GetType().Name); } }
public CollectionFromInt(IReadOnlyReactiveProperty <int> count) { _count = count; _currentCount = _count.Value; count.Subscribe(newCount => { var difference = newCount - _currentCount; if (difference > 0) { for (var i = 0; i < difference; i++) { _observeAdd.OnNext(new CollectionAddEvent <Unit>(_currentCount + i, Unit.Default)); } } else if (difference < 0) { for (var i = 0; i < difference; i++) { _observeRemove.OnNext(new CollectionRemoveEvent <Unit>(_currentCount - i - 1, Unit.Default)); } } _currentCount = newCount; }); }
/// <summary> /// オブジェクトのプロパティから MovableValueViewModel を作成する。 /// </summary> /// <typeparam name="T"> /// オブジェクト型。 /// INotifyPropertyChanged インタフェースを実装している必要がある。 /// </typeparam> /// <typeparam name="TConstants">定数情報型。</typeparam> /// <param name="holder">オブジェクト。</param> /// <param name="selector"> /// オブジェクトの MovableValue{TConstants} プロパティセレクタ。 /// </param> /// <param name="name">名前。 null ならば自動決定される。</param> /// <returns>MovableValueViewModel 。</returns> private MovableValueViewModel MakeMovableValueViewModel <T, TConstants>( IReadOnlyReactiveProperty <T> holder, Expression <Func <T, MovableValue <TConstants> > > selector, string name = null) where T : INotifyPropertyChanged where TConstants : IMovableValueConstants, new() { Debug.Assert(holder != null); Debug.Assert(selector != null); // 値取得 var value = this.MakeInnerPropertyOf(holder, selector, this.CanModify); // 名前取得 var info = ((MemberExpression)selector.Body).Member; name = name ?? info.GetCustomAttribute <ExoFileItemAttribute>(true)?.Name ?? info.Name; return (new MovableValueViewModel(this.CanModify, value, name) .AddTo(this.CompositeDisposable)); }
protected void Start() { m_selectable = GetComponent <Selectable>(); IReadOnlyReactiveProperty <bool> property = GetProperty <bool>(); property.TakeUntilDestroy(this).SubscribeToInteractable(m_selectable).AddTo(this); }
public GambitList(GambitListInfo gambitListInfo) { this._gambitListInfo = gambitListInfo; moveInput = new Subject <Vector3>(); targets = new ReactiveProperty <object>(); }
private IObservable <AudioEventType> OnAudioEventAsObservable() { TimePair = AudioSource .ObserveEveryValueChanged(x => x.time) .Pairwise() .ToReactiveProperty(); switch (AudioEventType) { case AudioEventType.Play: case AudioEventType.Stop: case AudioEventType.Pause: case AudioEventType.UnPause: return(AudioSource .ObserveEveryValueChanged(x => x.isPlaying) .Select(x => DetectAudioEventType(x, AudioSource.clip)) .Where(x => AudioEventType == x)); case AudioEventType.Loop: return(TimePair .Where(xs => AudioSource.isPlaying && xs.Current < xs.Previous && xs.Previous > 0.0f) .Select(_ => AudioEventType.Loop)); default: throw new ArgumentOutOfRangeException(); } }
public WebcamOverlay(WebcamModel WebcamModel, Settings Settings) : base(true) { _webcamModel = WebcamModel; _settings = Settings.WebcamOverlay; _webcamCapture = WebcamModel.InitCapture(); }
public CollectibleViewModel(Collectible item, IReadOnlyReactiveProperty <string> searchtText, IList <Tag> tags) { OriginalTitle = item.Title; Tags = item.Tags.Select(t => new TagViewModel(t, this)).ToReactiveCollection(); TagsCount = Tags.ObserveCountChanged(true).ToReadOnlyReactiveProperty(); AddRandomTag = new ReactiveCommand(TagsCount.Select(t => t < 2)); AddRandomTag.Subscribe(_ => Tags.Add(new TagViewModel(tags[Random.Range(0, tags.Count - 1)], this))); IsSelected = new ReactiveProperty <bool>(); Title = searchtText.Select(searchVal => { if (string.IsNullOrEmpty(searchVal)) { return(OriginalTitle); } try { return(Regex.Replace(OriginalTitle, "(" + searchVal .Replace("[", "\\[") .Replace("]", "\\]") .Replace("(", "\\(") .Replace(")", "\\)") + ")", "<b>$1</b>", RegexOptions.IgnoreCase)); } catch (Exception e) { return(OriginalTitle); } }).ToReadOnlyReactiveProperty(); }
public override void AlwaysStart() { IReadOnlyReactiveProperty <bool> property = GetProperty <bool>(); (from active in property.TakeWhile((bool _) => this != null) select active == m_activeOnTrue).SubscribeToActiveUntilNull(base.gameObject).AddTo(this); }
/// <summary> /// ■brakePower:ブレーキの強さ /// </summary> public EngineSpeedCalc(VehicleSettings.EngineSettings engineSettings, VehicleSettings.PenaltySettings penaltySettings, GearParam gearParam, IReadOnlyReactiveProperty <GearState> gear) { mEngineSettings = engineSettings; mPenaltySettings = penaltySettings; mCurrentGear = gear; mLowestSpeed = gearParam.GetGearData(GearState.REVERSE).MaxSpeed; mEngineRpmCalculator = new EngineRpmCalculator(gearParam, gear); mCurrentGear .Buffer(2, 1) .Subscribe(x => { //現在のギアデータ GearData gearData = gearParam.GetGearData(x.Last()); //1つ前のギアデータ GearData lateGearData = gearParam.GetGearData(x.First()); //現在のギアに必要な回転数を取得 mNeedSpeed = gearData.NeedSpeed; //現在のギアの最大回転数を取得 mMaxSpeed = gearData.MaxSpeed; //ギア変更前の最大回転数を取得 mPreMaxSpeed = lateGearData.MaxSpeed; //エンジンブレーキの強さを取得 mEngineBrakePow = gearData.EngineBrake; //1秒あたりのエンジン回転数を取得 mAccPow = gearData.EngineRot; }); }
/// <summary> /// インスタンスを生成します。 /// </summary> /// <param name="nextTetrimino">次のテトリミノ</param> public NextFieldViewModel(IReadOnlyReactiveProperty <TetriminoKind> nextTetrimino) { //--- 描画するセルを準備 this.Cells = new CellViewModel[This.RowCount, This.ColumnCount]; foreach (var item in this.Cells.WithIndex()) { this.Cells[item.X, item.Y] = new CellViewModel(); } //--- ブロックに関する変更を処理 nextTetrimino .Select(x => Tetrimino.Create(x).Blocks.ToDictionary2(y => y.Position.Row, y => y.Position.Column)) .Subscribe(x => { //--- ViewPort のオフセット調整 //--- ちゃんと書くのがだいぶ面倒臭くなったから無理やりやる var offset = new Position((-6 - x.Count) / 2, 2); //--- 適用 foreach (var item in this.Cells.WithIndex()) { var color = x.GetValueOrDefault(item.X + offset.Row) ?.GetValueOrDefault(item.Y + offset.Column) ?.Color ?? this.BackgroundColor; item.Element.Color.Value = color; } }); }
public CombineAllValueViewModel() { CheckAllTrue = new IObservable <bool>[] { Check1, Check2, Check3 } .CombineLatestValuesAreAllTrue() .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); CheckAllFalse = new IObservable <bool>[] { Check1, Check2, Check3 } .CombineLatestValuesAreAllFalse() .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); CheckOr = new IObservable <bool>[] { Check1, Check2, Check3 } .CombineLatest() .Select(flags => flags.Any(x => x)) .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); CheckOdd = new IObservable <bool>[] { Check1, Check2, Check3.Inverse().Inverse() } // NotNotなので意味なし .CombineLatest() .Select(flags => { var count = 0; foreach (var flag in flags) { if (flag) { ++count; } } return((count & 1) == 1); }) .ToReadOnlyReactiveProperty() .AddTo(CompositeDisposable); }
public void Serialize(ref MessagePackWriter writer, IReadOnlyReactiveProperty <T> value, MessagePackSerializerOptions options) { var rxProp = value as ReactiveProperty <T>; if (rxProp != null) { ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactiveProperty <T> >().Serialize(ref writer, rxProp, options); return; } var slimProp = value as ReactivePropertySlim <T>; if (slimProp != null) { ReactivePropertyResolver.Instance.GetFormatterWithVerify <ReactivePropertySlim <T> >().Serialize(ref writer, slimProp, options); return; } if (value == null) { writer.WriteNil(); } else { throw new InvalidOperationException("Serializer only supports ReactiveProperty<T> or ReactivePropertySlim<T>. If serialize is ReadOnlyReactiveProperty, should mark [Ignore] and restore on IMessagePackSerializationCallbackReceiver.OnAfterDeserialize. Type:" + value.GetType().Name); } }
protected override void OnInitialized() { base.OnInitialized(); _observable = Observe(OnTick); _value = _observable.ToReadOnlyReactiveProperty(); }
/// <summary> /// UI設定周りのセットアップを行う。 /// </summary> /// <param name="uiConfig">UI設定値。</param> private void SetupUIConfig(IReadOnlyReactiveProperty <UIConfig> uiConfig) { // 設定変更時に選択中キャラ別スタイル反映 Observable .CombineLatest( this.VisibleCharaStyles, uiConfig .ObserveInnerProperty(c => c.ExoCharaVoiceroidId) .DistinctUntilChanged(), (vcs, id) => vcs.FirstOrDefault(s => s.VoiceroidId == id) ?? vcs.First()) .DistinctUntilChanged() .Subscribe(s => this.SelectedCharaStyle.Value = s) .AddTo(this.CompositeDisposable); // 選択中キャラ別スタイル変更時処理 this.SelectedCharaStyle .Where(s => s != null) .Subscribe(s => uiConfig.Value.ExoCharaVoiceroidId = s.VoiceroidId) .AddTo(this.CompositeDisposable); this.SelectedCharaStyle .Where(s => s == null) .ObserveOnUIDispatcher() .Subscribe( _ => this.SelectedCharaStyle.Value = this.BaseConfig.Value.CharaStyles.First( s => s.VoiceroidId == uiConfig.Value.ExoCharaVoiceroidId)) .AddTo(this.CompositeDisposable); }
public FpsCounterViewModel() { MouseDownUnit = new ReactivePropertySlim <Unit>(mode: ReactivePropertyMode.None).AddTo(CompositeDisposable); // http://reactivex.io/documentation/operators/buffer.html // Buffer(count, skip) : count個のデータが溜まったら、skip個ごとに count個をまとめた List<T> を流します // Buffer(count) : countの倍数で、count個をまとめた List<T> を流します。 FpsCounter1 = MouseDownUnit .Select(_ => DateTime.Now) .Pairwise() .Select(dateTime => dateTime.NewItem - dateTime.OldItem) .Buffer(count: _bufferLength, skip: 1) .Select(tss => 1000d / tss.Select(ts => ts.TotalMilliseconds).Average()) .ToReadOnlyReactivePropertySlim() .AddTo(CompositeDisposable); FpsCounter2 = MouseDownUnit .TimeInterval() .Buffer(count: _bufferLength, skip: 1) .Select(xs => 1000d / xs.Select(x => x.Interval.Milliseconds).Average()) .ToReadOnlyReactivePropertySlim() .AddTo(CompositeDisposable); FpsCounter3 = MouseDownUnit .Framerate(_bufferLength) .ToReadOnlyReactivePropertySlim() .AddTo(CompositeDisposable); }
public ViewModel(ReactiveProperty <int> x, IReactiveProperty <int> y, IReadOnlyReactiveProperty <int> z) { Prop1 = x; Prop2 = y; Prop3 = z; OnAfterDeserialize(); }
public AssetSampleViewModel(IAssetService assetService) { var loadingText = new ReactiveProperty <string>(); AssetText = loadingText.ToReadOnlyReactiveProperty("Loading Text..."); loadingText.Value = assetService.ReadAssetText("Text/asset_sample_text_file.txt"); }
public static IDisposable Bind <T>(Action <T> propertyASetter, IReadOnlyReactiveProperty <T> propertyB, params IFilter <T>[] filters) { return(propertyB .ApplyInputFilters(filters) .DistinctUntilChanged() .Subscribe(propertyASetter)); }
/// <summary> /// Waits the until value changed asynchronous. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static async Task <T> WaitUntilValueChangedAsync <T>(this IReadOnlyReactiveProperty <T> source, CancellationToken cancellationToken = default(CancellationToken)) { using (var handler = GetAsyncHandler <T>(source, cancellationToken)) { return(await handler); } }
static FPSCounter() { Current = Observable.EveryUpdate() .Select(_ => Time.deltaTime) .Buffer(BufferSize, 1) .Select(x => 1.0f / x.Average()) .ToReadOnlyReactiveProperty(); }