Exemplo n.º 1
0
    public void PostInit()
    {
        SceneLoader instance = SceneLoader.Instance;

        DrillAdCooldown = (from _ in TickerService.MasterTicksSlow
                           select(float) Singleton <AdRunner> .Instance.GetNextTimeToShowAd(AdPlacement.Drill).TotalSeconds into secsLeft
                           select(int) Mathf.Max(0f, secsLeft)).DistinctUntilChanged().TakeUntilDestroy(instance).ToReactiveProperty();
        DrillAdAvailable = (from avail in DrillAdCooldown.CombineLatest(PlayerData.Instance.DrillLevel, (int cd, int lvl) => cd <= 0 && lvl < m_maxDrillAds)
                            select(avail)).CombineLatest(Singleton <AdRunner> .Instance.AdReady, (bool time, bool ad) => time && ad).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DrillAdCooldownLeft = DrillAdCooldown.Select(delegate(int seconds)
        {
            string empty = string.Empty;
            return((seconds > 0) ? TextUtils.FormatSecondsShort(seconds) : PersistentSingleton <LocalizationService> .Instance.Text("AD.Placement.NotAvailable"));
        }).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        (from ad in Singleton <AdRunner> .Instance.AdPlacementFinished
         where ad == AdPlacement.Drill
         select ad).Subscribe(delegate
        {
            DrillAdFinished();
        }).AddTo(instance);
        (from ad in Singleton <AdRunner> .Instance.AdPlacementSkipped
         where ad == AdPlacement.Drill
         select ad).Subscribe(delegate
        {
            DrillAdSkipped();
        }).AddTo(instance);
        (from ad in Singleton <AdRunner> .Instance.AdPlacementFailed
         where ad == AdPlacement.Drill
         select ad).Subscribe(delegate
        {
            DrillAdSkipped();
        }).AddTo(instance);
    }
	void Awake () {
		select_subscription = selected_scores.Subscribe((s)=>{
			if (s != null){
				if (date_time != null)
					date_time.text = s.time.date_recorded_local().ToString();
				//Yeah, it's ugly abuse of static variables, but I'll fix it later.
				score = s;
				MenuStateMachine.fsm.trigger_transition("scores->details");
			}
		});
		
		rx_player_name = rx_score.SelectMany(s=>{
			if (s == null)
				return Observable.Never<String>();
			return s.rx_player_name.AsObservable();
		}).CombineLatest(LanguageController.controller.rx_load_text("score_default_name"), (name, default_name)=>{
			if (IsNullOrWhiteSpace(name))
				return default_name;
			return name;
		}).ToReadOnlyReactiveProperty<string>();
		
		rx_player_name.Subscribe(t=>{
			if (player_name != null)
				player_name.text = t;
		});
	}
Exemplo n.º 3
0
    public ChunkRunner()
    {
        Singleton <PropertyManager> .Instance.AddRootContext(this);

        m_raycastMask = 1 << LayerMask.NameToLayer("Blocks");
        SceneLoader    instance = SceneLoader.Instance;
        BindingManager bind     = BindingManager.Instance;

        ShowNotification = (from _ in BlocksClearTriggered
                            select true).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        BlocksAmount = (from amount in AllBlockAmount
                        select(!(BossBlock.Value == null)) ? Mathf.Max(0, amount - 1) : amount).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        (from custom in CustomLevel
         where custom
         select custom).Subscribe(delegate
        {
            bind.CustomLevelNode.SetActive(value: true);
        }).AddTo(instance);
        (from custom in CustomLevel.Pairwise()
         where !custom.Current && custom.Previous
         select custom).Subscribe(delegate
        {
            bind.CustomLevelNode.SetActive(value: false);
            bind.CustomLevelFinishedNode.SetActive(value: true);
        }).AddTo(instance);
        (from custom in CustomLevel.Pairwise()
         where !custom.Current && !custom.Previous
         select custom).Subscribe(delegate
        {
            bind.CustomLevelNode.SetActive(value: false);
            bind.CustomLevelFinishedNode.SetActive(value: false);
        }).AddTo(instance);
        ChunkProgress   = CurrentChunkHealth.CombineLatest(ChunkMaxHealth, (BigDouble curr, BigDouble max) => (curr / max).ToFloat()).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        ChunkHealthText = CurrentChunkHealth.CombineLatest(ChunkMaxHealth, (BigDouble curr, BigDouble max) => BigString.ToString(curr) + " / " + BigString.ToString(max)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
    }
Exemplo n.º 4
0
        public Service(Oanda.RestClient restClient, string[] instruments)
        {
            this.restClient  = restClient;
            this.mt4Commands = new Subject <MT4.Command>();
            var prices = this.restClient.GetPriceStream(instruments);

            this.Instruments = new ReadOnlyDictionary <string, Instrument>(
                instruments
                .Select(name => {
                var ps = prices.Where(p => p.InstrumentName == name);
                var cs = this.mt4Commands.Where(c => c.Instrument == name);
                return(new Instrument(name, ps, cs));
            })
                .ToDictionary(instrument => instrument.Name)
                );
            var events = this.restClient.GetEventStream().Merge(Observable.Return <object>(null));

            this.Account = events
                           .SelectMany(_ => this.restClient.GetAccount())
                           .ToReadOnlyReactiveProperty()
            ;
            this.Positions = events
                             .SelectMany(_ => this.restClient.GetPositions())
                             .ToReadOnlyReactiveProperty()
            ;
        }
Exemplo n.º 5
0
 public ListControl()
 {
     Views  = _reactiveViews.ToReadOnlyReactiveProperty();
     Models = _models
              .Select(x => new ReadOnlyCollection <object>(x))
              .ToReadOnlyReactiveProperty();
 }
Exemplo n.º 6
0
    void Start()
    {
        // Distance display
        _distance = new ReadOnlyReactiveProperty <float>(Observable.EveryUpdate().Select(_ =>
                                                                                         Vector3.Distance(player.transform.position, mob.transform.position)));
        _distance.SubscribeToText(this.distanceText);

        // Mob chase player every update
        Observable.EveryUpdate().Subscribe(_ =>
                                           mob.direction.Value = (player.transform.position - mob.transform.position).normalized);

        // Time sequence of 1/1, 1/2, 1/3, 1/4...
        var fracTimeSequence = Observable.Create <float>(observer =>
        {
            var i = 1;
            return(Scheduler.DefaultSchedulers.TimeBasedOperations.Schedule(System.TimeSpan.FromSeconds(this.initialTime / i), self =>
            {
                observer.OnNext(i % 2 == 0 ? 1.0f : -1.0f);
                i++;
                self(System.TimeSpan.FromSeconds(this.initialTime / i));
            }));
        });

        fracTimeSequence.Subscribe(_ => this.player.direction.Value = Vector3.Cross(Vector3.back, this.mob.direction.Value).normalized);
    }
Exemplo n.º 7
0
        public AppModel()
        {
            CubeTransform = InitializeCubeTransform();

            var inclinometer = Inclinometer.GetDefault();

            if (inclinometer != null)
            {
                inclinometer.ReportInterval  = 200;
                inclinometer.ReadingChanged += (o, e) => InclinationData.Value = e.Reading;
            }

            var orientationSensor = OrientationSensor.GetDefault();

            if (orientationSensor != null)
            {
                orientationSensor.ReportInterval  = 200;
                orientationSensor.ReadingChanged += (o, e) => OrientationData.Value = e.Reading;
            }

            RotationQuaternion       = OrientationData.Select(d => d.Quaternion.ToQuaternion()).ToReadOnlyReactiveProperty();
            RotationQuaternionString = RotationQuaternion.Select(q => $"{q.W:F2}; ({q.X:F2}, {q.Y:F2}, {q.Z:F2})").ToReadOnlyReactiveProperty();

            // Rotation is represented by a matrix, a quaternion or Euler angles (roll, pitch and yaw).
            RotationMatrix = OrientationData.Select(d => d.RotationMatrix.ToMatrix3D()).ToReadOnlyReactiveProperty();
            //RotationMatrix = RotationQuaternion.Select(q => q.ToMatrix3D()).ToReadOnlyReactiveProperty();
            //RotationMatrix = InclinationData.Select(i => i.ToMatrix3D()).ToReadOnlyReactiveProperty();

            // An inverse matrix represents the inverse rotation.
            RotationMatrix
            .ObserveOn(SynchronizationContext.Current)
            //.Subscribe(m => matrixTransform.Matrix = m);
            .Subscribe(m => { m.Invert(); matrixTransform.Matrix = m; });
        }
Exemplo n.º 8
0
    public BoosterRunner(int booster)
    {
        SceneLoader instance = SceneLoader.Instance;

        BoosterIndex    = booster;
        m_boosterConfig = PersistentSingleton <Economies> .Instance.Boosters[BoosterIndex];
        if (BoosterIndex == 0)
        {
            m_maxBoosterAmount = PersistentSingleton <GameSettings> .Instance.MaxDamageBoosterPurchaseAmount;
        }
        else
        {
            m_maxBoosterAmount = PersistentSingleton <GameSettings> .Instance.MaxBoosterPurchaseAmount;
        }
        BoosterMaxReached = (from currentAmount in PlayerData.Instance.BoostersBought[BoosterIndex]
                             select currentAmount >= m_maxBoosterAmount).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        BoosterCost = (from amount in PlayerData.Instance.BoostersBought[BoosterIndex]
                       select Singleton <EconomyHelpers> .Instance.GetBoosterCost(BoosterIndex, amount)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        BoosterAvailable  = BoosterCost.CombineLatest(PlayerData.Instance.Gems, (int cost, int gems) => cost <= gems).TakeUntilDestroy(instance).ToSequentialReadOnlyReactiveProperty();
        BoosterName.Value = PersistentSingleton <LocalizationService> .Instance.Text("GemBooster.Title." + (BoosterEnum)BoosterIndex);

        BoosterDescription.Value = PersistentSingleton <LocalizationService> .Instance.Text("GemBooster.Desc." + (BoosterEnum)BoosterIndex);

        BoosterBonus = (from _ in PlayerData.Instance.BoostersEffect[BoosterIndex]
                        select BoosterCollectionRunner.GetBoosterBonusString((BoosterEnum)BoosterIndex)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        BoosterNextUpgrade = (from _ in BoosterCost
                              select BoosterCollectionRunner.GetBoosterNextUpgradeString((BoosterEnum)BoosterIndex)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        ActiveBooster = (from active in Singleton <BoosterCollectionRunner> .Instance.ActiveBooster
                         select active == BoosterIndex).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
    }
Exemplo n.º 9
0
 public Person(string givenName, string familyName)
 {
     GivenName  = new ReactiveProperty <string>(givenName);
     FamilyName = new ReactiveProperty <string>(familyName);
     // If change the givenName or familyName, notify with fullName!
     FullName = GivenName.CombineLatest(FamilyName, (x, y) => x + " " + y).ToReadOnlyReactiveProperty();
 }
Exemplo n.º 10
0
        public NotifyWindowViewModel(Window ownerWindow)
        {
            this._mainWindow = ownerWindow as MainWindow;
            if (this._mainWindow == null)
            {
                throw new ArgumentException(nameof(ownerWindow));
            }

            var mainWindowViewModel = this._mainWindow.DataContext as MainWindowViewModel;

            this.Profiles = mainWindowViewModel.Profiles;

            IsAnyConnected = this.Profiles
                             .ObserveElementObservableProperty(x => x.IsConnected)
                             .ObserveOnUIDispatcher()
                             .Select(_ =>
            {
                this.ProfilesView.Refresh();
                return(this.ProfilesView.Count > 0);
            })
                             .ToReadOnlyReactiveProperty()
                             .AddTo(this.Subscription);

            mainWindowViewModel.ReloadCommand.Execute();
        }
Exemplo n.º 11
0
        public UserModel()
        {
            LoggedInUser = new ReactiveProperty <Type.LoggedInUser>();

            HasLoggedIn = LoggedInUser.Select(u => u != null).ToReadOnlyReactiveProperty();
            Name        = LoggedInUser.Select(u => u == null ? string.Empty : u.Name).ToReadOnlyReactiveProperty();
        }
Exemplo n.º 12
0
        public UnitViewModel(UnitConfig config, UnitModel model, ResourcePackViewModel resources)
        {
            Assert.IsNotNull(config, nameof(config));
            Assert.IsNotNull(model, nameof(model));
            Assert.IsNotNull(resources, nameof(resources));

            _config       = config;
            _model        = model;
            _resources    = resources;
            _sprite       = new ReactiveProperty <Sprite>();
            Sprite        = _sprite.ToReadOnlyReactiveProperty();
            _level        = new ReactiveProperty <int>(_model.Level);
            Level         = _level.ToReadOnlyReactiveProperty();
            Income        = new ResourceViewModel(model.Income);
            _upgradePrice = new ReactiveProperty <ResourceViewModel>(GetUpgradePrice());
            UpgradePrice  = _upgradePrice.ToReadOnlyReactiveProperty();
            _canUpgrade   = new ReactiveProperty <bool>(IsUpgradeAvailable());
            CanUpgrade    = _canUpgrade.ToReadOnlyReactiveProperty();
            foreach (var resource in resources.Resources)
            {
                resource.Value.Amount
                .Select(_ => IsUpgradeAvailable())
                .Subscribe(isAvailable => _canUpgrade.Value = isAvailable);
            }

            Level
            .Do(l => _model.Level = l)
            .Subscribe(OnLevelUpdated);
        }
Exemplo n.º 13
0
    private void Awake()
    {
        Jump = this.UpdateAsObservable()
               .Where(_ => Input.GetButtonDown("Jump"));
        var jumpLatch = CustomObservables.Latch(this.FixedUpdateAsObservable(), Jump, false);

        Movement = this.FixedUpdateAsObservable()
                   .Select(_ =>
        {
            float x       = Input.GetAxis("Horizontal");
            float y       = Input.GetAxis("Vertical");
            Vector2 dir2D = new Vector2(x, y);
            return(dir2D);
        });

        MoveInputs = Movement.Zip(jumpLatch, (movement, jump) => new MovementInputs(movement, jump));

        Rotation = this.UpdateAsObservable()
                   .Select(_ =>
        {
            float mouseX = Input.GetAxis("Mouse X");
            float mouseY = Input.GetAxis("Mouse Y");
            return(new Vector2(mouseX, mouseY));
        });

        Run = this.UpdateAsObservable()
              .Select(_ =>
        {
            return(Input.GetButton("Fire3"));
        }).ToReadOnlyReactiveProperty();
    }
Exemplo n.º 14
0
        public GameViewModel(IModel model) : base(model)
        {
            _isPause = new ReactiveProperty <bool>(false);
            IsPause  = new ReadOnlyReactiveProperty <bool>(_isPause);

            InitLevelCommand           = new ReactiveCommand <int>();
            PlayerGetDamageCommand     = new ReactiveCommand <int>();
            SetPauseCommand            = new ReactiveCommand <bool>();
            ChangePlayerAttemptCommand = new ReactiveCommand();
            ResetPlayerHpCommand       = new ReactiveCommand();
            FinishLevelCommand         = new ReactiveCommand();

            InitLevelCommand.Subscribe(InitNewLevelGameData);
            SetPauseCommand.Subscribe(isPause =>
            {
                _isPause.Value = isPause;
            });
            ChangePlayerAttemptCommand.Subscribe(_ =>
            {
                _playerAttempts.Value -= 1;
            });
            ResetPlayerHpCommand.Subscribe(_ =>
            {
                _playerHp.Value = Model.GameData.StartPlayerHp;
            });
            PlayerGetDamageCommand.Subscribe(_ =>
            {
                _playerHp.Value -= 1;
            });
            FinishLevelCommand.Subscribe(_ =>
            {
                Model.PlayerInGameValue.Value += LevelSettings.LevelInGameValuePrice;
                Model.PlayerPassedLevel.Value++;
            });
        }
Exemplo n.º 15
0
    // Use this for initialization
    protected override void Awake()
    {
        base.Awake();

        var hinf = new RaycastHit();

        Grounded = Observable.EveryFixedUpdate()
                   .Select(_ => Physics.Raycast(RaycastOrigin, Vector3.down, out hinf, Level.Instance.DistBetweenAnchors, LayerMask.GetMask("Bounds", "Blocks", "Characters")))
                   .ToReadOnlyReactiveProperty(true);

        Grounded.AddTo(this);

        Grounded.Subscribe(x => Anim.SetBool("Falling", !x));

        ObservableHP = this.ObserveEveryValueChanged(x => x.CurHp)
                       .ToReadOnlyReactiveProperty(CurHp);

        IsDead = ObservableHP
                 .Select(x => x <= 0)
                 .ToReadOnlyReactiveProperty(false);

        Rb.OnCollisionEnterAsObservable()
        .Select(c => c.collider.GetComponentInParent <GameCharacter>())
        .Where(gc => gc && (gc.transform.position - transform.position).y < -Level.Instance.DistBetweenAnchors * .5f)
        .TakeUntil(IsDead.Where(x => x))
        .Subscribe(gc =>
        {
            target.Value = gc;
            gc.GetHit();
            Rb.AddForce(Vector3.up * 3.5f, ForceMode.Impulse);
        })
        .AddTo(this);
    }
Exemplo n.º 16
0
 protected void bindPreloading(List <FlooredAdProvider> placements)
 {
     if (placements.Count != 0)
     {
         ReactiveProperty <bool>         highestFloorHasAd = placements.First().AdsReady;
         ReadOnlyReactiveProperty <long> source            = (from r in highestFloorHasAd
                                                              where !r
                                                              select r into _
                                                              select ServerTimeService.NowTicks()).ToReadOnlyReactiveProperty();
         UniRx.IObservable <long> source2 = (from _ in source
                                             select Observable.Return(0L).Concat(Observable.Interval(TimeSpan.FromSeconds(preloadNotAvailableWaitingPeriod))).TakeUntil(from r in highestFloorHasAd
                                                                                                                                                                        where r
                                                                                                                                                                        select r)).Switch();
         FlooredAdProvider backFiller = placements.Last();
         (from _ in source2
          where !backFiller.AdsReady.Value
          select _).Subscribe(delegate
         {
             preload(backFiller);
         }).AddTo(_disposable);
         FlooredAdProvider[] flooredPlacements = (from p in placements
                                                  where p != backFiller
                                                  select p).ToArray();
         if (flooredPlacements.Length > 0)
         {
             (from _ in source2
              select(from p in flooredPlacements
                     select UniRx.Tuple.Create(p, flooredPlacements.TakeWhile((FlooredAdProvider pr) => pr != p))).ToObservable().SelectMany((UniRx.Tuple <FlooredAdProvider, IEnumerable <FlooredAdProvider> > pair) => Observable.Return(pair).Delay(TimeSpan.FromSeconds(waitTimeForTheNextProvider * pair.Item2.Count())).SelectMany((UniRx.Tuple <FlooredAdProvider, IEnumerable <FlooredAdProvider> > p) => Observable.Return(p).TakeUntil(previousOrMeGotReady(pair.Item1, pair.Item2))))).Switch().Subscribe(delegate(UniRx.Tuple <FlooredAdProvider, IEnumerable <FlooredAdProvider> > p)
             {
                 preload(p.Item1);
             }).AddTo(_disposable);
         }
     }
 }
Exemplo n.º 17
0
        public TodoUsecase(ITodoRepository todoRepository)
        {
            this.todoRepository = todoRepository;

            IsVisibleDone = IsVisibleDoneInternal.ToReadOnlyReactiveProperty();
            TodoItems     = TodoItemsInternal.ToReadOnlyReactiveCollection();
        }
Exemplo n.º 18
0
    public void PostInit()
    {
        SceneLoader instance = SceneLoader.Instance;

        AdTime = (from _ in TickerService.MasterTicks
                  select(float) Singleton <AdRunner> .Instance.GetNextTimeToShowAd(AdPlacement.HammerTime).TotalSeconds into secsLeft
                  select(int) Mathf.Max(0f, secsLeft)).DistinctUntilChanged().TakeUntilDestroy(instance).ToReactiveProperty();
        AdAvailable = (from time in AdTime
                       select time <= 0).CombineLatest(Singleton <AdRunner> .Instance.AdReady, (bool time, bool ad) => time && ad).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        AdTimeLeft = AdTime.Select(delegate(int seconds)
        {
            string empty = string.Empty;
            return((seconds > 0) ? TextUtils.FormatSecondsShort(seconds) : PersistentSingleton <LocalizationService> .Instance.Text("AD.Placement.NotAvailable"));
        }).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        (from ad in Singleton <AdRunner> .Instance.AdPlacementFinished
         where ad == AdPlacement.HammerTime
         select ad).Subscribe(delegate
        {
            HammerTimeAdFinished();
        }).AddTo(instance);
        (from ad in Singleton <AdRunner> .Instance.AdPlacementSkipped
         where ad == AdPlacement.HammerTime
         select ad).Subscribe(delegate
        {
            HammerTimeAdSkipped();
        }).AddTo(instance);
        (from ad in Singleton <AdRunner> .Instance.AdPlacementFailed
         where ad == AdPlacement.HammerTime
         select ad).Subscribe(delegate
        {
            HammerTimeAdSkipped();
        }).AddTo(instance);
    }
Exemplo n.º 19
0
        public AppModel()
        {
            // JPEG ファイルは DPI が異なる場合があります (既定では 96 だが、72 などもある)。
            // Image コントロールに直接読み込ませると、DPI によりサイズが変化してしまいます。
            ImageUrl
            .Subscribe(u =>
            {
                var image = new BitmapImage(new Uri(u));

                // ダウンロードの要否で分岐します。
                if (image.IsDownloading)
                {
                    image.DownloadCompleted += (o, e) => BitmapImage.Value = image;
                }
                else
                {
                    BitmapImage.Value = image;
                }
            });
            ImageUrl
            .Subscribe(_ => DetectAsync());

            IsImageEmpty = ImageUrl
                           .Select(u => u == null)
                           .ToReadOnlyReactiveProperty(true);
        }
Exemplo n.º 20
0
 public LapTimeViewModel(int countOfLap, TimeSpan lapTime)
 {
     CountOfLap = new ReactiveProperty <int>(countOfLap)
                  .ToReadOnlyReactiveProperty();
     LapTime = new ReactiveProperty <TimeSpan>(lapTime)
               .ToReadOnlyReactiveProperty();
 }
Exemplo n.º 21
0
    public GearSetCollectionRunner()
    {
        Singleton <PropertyManager> .Instance.AddRootContext(this);

        SceneLoader instance = SceneLoader.Instance;

        for (int i = 0; i < 25; i++)
        {
            BonusMult[i] = CreateObservableForAll((BonusTypeEnum)i).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        }
        ReactiveProperty <int> mainChunk = PlayerData.Instance.LifetimeChunk;

        MaxSetsToShow = (from lvl in mainChunk
                         select GetMaxSetsToShow(lvl)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        SetUnlocked = (from pair in MaxSetsToShow.Pairwise()
                       where pair.Previous < pair.Current
                       select pair into _
                       select GetUnlockedGears(mainChunk.Value)).Do(delegate
        {
            BindingManager.Instance.HeroLevelParent.ShowInfo();
        }).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        NextSetUnlockAt = (from lvl in mainChunk
                           select GetNextSetUnlockAt(lvl)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        AllSetsUnlocked = (from lvl in mainChunk
                           select IsAllSetsUnlocked(lvl)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        AllAvailableGearsUnlocked = (from unlockAvailable in (from lvl in mainChunk
                                                              select GetMaxSetsToShow(lvl)).CombineLatest(PlayerData.Instance.LifetimeGears, (int maxSets, int unlocks) => maxSets * 3 > unlocks)
                                     select !unlockAvailable).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
    }
Exemplo n.º 22
0
        public StopWatchModel()
        {
            Debug.WriteLine("StopWatchModel ctor");

            IsRunning       = _isRunning.ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default);
            IsVisibleMillis = _isVisibleMillis;

            _timeFormat = IsVisibleMillis
                          .Select(v => v ? @"mm\:ss\.fff" : @"mm\:ss")
                          .ToReactiveProperty(raiseEventScheduler: Scheduler.Default);

            FormattedTime = _time.CombineLatest(_timeFormat, (time, format) =>
                                                TimeSpan.FromMilliseconds(time).ToString(format))
                            .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default);

            FormattedLaps = _laps.CombineLatest(_timeFormat,
                                                (laps, f) => laps.Select((x, i) => TimeSpan.FromMilliseconds(x).ToString(f)))
                            .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default);

            FormattedFastestLap = _laps.CombineLatest(_timeFormat, (laps, format) =>
            {
                var fastest = laps.Count > 0 ? laps.Min() : 0;
                return(TimeSpan.FromMilliseconds(fastest).ToString(format));
            })
                                  .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default);

            FormattedWorstLap = _laps.CombineLatest(_timeFormat, (laps, format) =>
            {
                var worst = laps.Count > 0 ? laps.Max() : 0;
                return(TimeSpan.FromMilliseconds(worst).ToString(format));
            })
                                .ToReadOnlyReactiveProperty(eventScheduler: Scheduler.Default);
        }
Exemplo n.º 23
0
 public Instrument(string name, IObservable <Oanda.Price> prices, IObservable <MT4.Command> commands)
 {
     this.Name        = name;
     this.Price       = prices.ToReadOnlyReactiveProperty();
     this.CurrentLine = commands
                        .Where(c => c.price != null || c.operation == "close")
                        .Select(c => (c.operation == "close") ? null : c.price)
                        .ToReadOnlyReactiveProperty()
     ;
     this.ChartLines = commands
                       .Where(c => c.lines != null || c.operation == "close")
                       .Scan(new Dictionary <long, MT4.Line[]>(), (a, c) =>
     {
         var ret = new Dictionary <long, MT4.Line[]>(a);
         if (c.operation == "close")
         {
             ret.Remove(c.chart);
         }
         else
         {
             ret[c.chart] = c.lines;
         }
         return(ret);
     })
                       .Select(d => new ReadOnlyDictionary <long, MT4.Line[]>(d))
                       .ToReadOnlyReactiveProperty()
     ;
 }
Exemplo n.º 24
0
    void Awake()
    {
        this.direction = new ReactiveProperty <Vector3>(Vector3.up);
        this.velocity  = new ReadOnlyReactiveProperty <Vector3>(this.direction.Select(dir => dir * this.speed));

        Observable.EveryUpdate().Subscribe(_ => this.transform.Translate(this.velocity.Value * Time.deltaTime));
    }
Exemplo n.º 25
0
        public AppModel()
        {
            CubeTransform = InitializeCubeTransform();

            FrontHand = LeapManager.FrameArrived
                        .Select(f => f.Hands.Frontmost)
                        .Select(h => h?.IsValid == true ? h : null)
                        .ToReadOnlyReactiveProperty();
            InnerProduct = FrontHand
                           .Select(h => h != null ? h.Direction.Dot(h.PalmNormal) : double.NaN)
                           .ToReadOnlyReactiveProperty();

            EulerAngles_org = FrontHand
                              .Select(h => h != null ? h.GetEulerAngles_org() : new EulerAngles())
                              .ToReadOnlyReactiveProperty();
            EulerAngles = FrontHand
                          .Select(h => h != null ? h.GetEulerAngles() : new EulerAngles())
                          .ToReadOnlyReactiveProperty();

            //Rotation = EulerAngles_org
            Rotation = EulerAngles
                       .Select(Rotation3DHelper.ToMatrix3D)
                       .ToReadOnlyReactiveProperty();

            Rotation
            .ObserveOn(SynchronizationContext.Current)
            .Subscribe(m => matrixTransform.Matrix = m);
        }
Exemplo n.º 26
0
        public NicoAccountIntroductionPageViewModel(HohoemaApp hohoema)
        {
            _HohoemaApp = hohoema;

            IsLoggedIn = _HohoemaApp.ObserveProperty(x => x.IsLoggedIn)
                         .ToReadOnlyReactiveProperty();
        }
 public BasicUsageViewModel()
 {
     Input  = new ReactiveProperty <string>("");
     Output = Input.Delay(TimeSpan.FromSeconds(1))
              .Select(x => x.ToUpper())
              .ToReadOnlyReactiveProperty();
 }
Exemplo n.º 28
0
 public CacheVideoViewModel(NicoVideo nicoVideo, PageManager pageManager)
     : base(nicoVideo, pageManager, isNgEnabled: false)
 {
     CacheRequestTime = nicoVideo.ObserveProperty(x => x.CachedAt)
                        .ToReadOnlyReactiveProperty()
                        .AddTo(_CompositeDisposable);
 }
Exemplo n.º 29
0
    public HammerTimeRunner()
    {
        Singleton <PropertyManager> .Instance.AddRootContext(this);

        SceneLoader            instance         = SceneLoader.Instance;
        ReactiveProperty <int> reactiveProperty = (from dur in PlayerData.Instance.BoostersEffect[5]
                                                   select(int) dur + PersistentSingleton <GameSettings> .Instance.GoldenHammerInitialDuration).TakeUntilDestroy(instance).ToReactiveProperty();
        ReactiveProperty <int> right = reactiveProperty.CombineLatest(PlayerData.Instance.HammerTimeBonusDuration, (int dura, int bonus) => dura + bonus).TakeUntilDestroy(instance).ToReactiveProperty();

        TickerService.MasterTicks.Subscribe(delegate(long ticks)
        {
            if (PlayerData.Instance.HammerTimeElapsedTime.Value < 1728000000000L)
            {
                PlayerData.Instance.HammerTimeElapsedTime.Value += ticks;
            }
        }).AddTo(instance);
        UniRx.IObservable <int> source = PlayerData.Instance.HammerTimeElapsedTime.CombineLatest(right, (long ticks, int dur) => dur - (int)(ticks / 10000000));
        Active = (from secs in source
                  select secs > 0).TakeUntilDestroy(instance).ToReactiveProperty();
        DurationLeft = (from seconds in source
                        select TextUtils.FormatSecondsShort(seconds)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        DurationString = (from dur in reactiveProperty
                          select PersistentSingleton <LocalizationService> .Instance.Text("Attribute.Duration") + ": " + BoosterCollectionRunner.FormatSecondsForBoosters(dur)).TakeUntilDestroy(instance).ToReadOnlyReactiveProperty();
        HammerTimeEnded = (from act in Active
                           select act && (HammerTimeActive = true) into sit
                           select(!sit && HammerTimeActive) ? true : false).TakeUntilDestroy(instance).ToReactiveProperty();
        (from elapsed in PlayerData.Instance.HammerTimeElapsedTime
         where elapsed < 0
         select elapsed).CombineLatest(right, (long cheat, int dur) => dur).Subscribe(delegate(int dur)
        {
            PlayerData.Instance.HammerTimeElapsedTime.Value = dur;
        }).AddTo(instance);
    }
Exemplo n.º 30
0
        public LobbyModel()
        {
            Rooms      = new ReactiveProperty <List <Type.Room> >(new List <Type.Room>());
            JoinedRoom = new ReactiveProperty <Type.JoinedRoom>();

            HasJoinedIntoRoom = JoinedRoom.Select(r => r != null).ToReadOnlyReactiveProperty();
        }
Exemplo n.º 31
0
        public override async void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);
            await this.Model.SetSelectedShopByIdAsync(e.Parameter as string);

            this.Disposable = new CompositeDisposable();

            this.Name = this.Model
                        .ObserveProperty(x => x.SelectedShop)
                        .Select(x => x?.name)
                        .ToReadOnlyReactiveProperty()
                        .AddTo(this.Disposable);

            this.Kana = this.Model
                        .ObserveProperty(x => x.SelectedShop)
                        .Select(x => x?.name_kana)
                        .ToReadOnlyReactiveProperty()
                        .AddTo(this.Disposable);

            this.Image = this.Model
                         .ObserveProperty(x => x.SelectedShop)
                         .Select(x => x?.photo?.pc?.l)
                         .ToReadOnlyReactiveProperty()
                         .AddTo(this.Disposable);
        }
		public QuickImportOption(string _name){
			option_name = _name;
			dropdown_option = new Dropdown.OptionData();
			
			rx_display_text = LanguageController.controller.rx_get_filename_label(_name);
			
			sub = rx_display_text.Subscribe(t=>{
				dropdown_option.text = t;
			});
		}
	void Start() {
		if (slider != null){
			rx_value = slider.OnValueChangedAsObservable().Select<float, float>(
				clamp_value).ToReadOnlyReactiveProperty<float>(clamp_value(slider.value));
			rx_value.Subscribe(
				value => {
					if (icon != null)
						icon.color = StrawberryColor.color_gradient.Evaluate(value);
				}
			);
		}
	}
	void init_visible(){
		if (obs_visible == null){
			init_status();
			init_parent();
			obs_visible = obs_parent.SelectMany((parent)=>{
				if (parent == null)
					return Observable.Return<bool>(true);
				parent.init_visible();
				return parent.obs_visible;
			}).CombineLatest(obs_status, (bool p_visible, VisibilityStatus stat)=>{
				if (stat == VisibilityStatus.AlwaysVisible) return true;
				if (stat == VisibilityStatus.NeverVisible) return false;
				return p_visible;
			}).ToReadOnlyReactiveProperty();
			obs_visible.DistinctUntilChanged().Subscribe(update);
		};
	}
	void Start(){
		rx_ripeness = rx_strawberry.Select(berry=>berry.ripeness).ToReadOnlyReactiveProperty<float>();
		rx_weight = rx_strawberry.Select(berry=>berry.weight).ToReadOnlyReactiveProperty<float>();
		rx_strawberry.Subscribe((berry) => {
			if (berry != null && win != null){
				vis.visible = true;
				color_icon.color = StrawberryColor.get_color(berry.ripeness);
				weight_text.text = berry.weight.ToString("0.00");
				
				ScoreTarget ripeness = win.ripeness;
				ScoreTarget berry_weight = win.berry_size;
				
				//Status Icon
				if (ripeness.is_accept(berry.ripeness)){
					if (berry_weight.is_accept(berry.weight)){
						status_icon.sprite = sprites["Accepted"];
					} else {
						status_icon.sprite = sprites["Undersize"];
					}
				} else {
					if (ripeness.is_over(berry.ripeness)){
						status_icon.sprite = sprites["Overripe"];
					} else {
						status_icon.sprite = sprites["Underripe"];
					}
				}
				
				//Score Views
				float flat_score = win.evaluate_strawberry_flat(berry);
				float range_score = win.evaluate_strawberry_range(berry);
				float total_score = win.evaluate_strawberry(berry);

				ScoreDetailedForm.format_score_text(flat_score_text, flat_score);
				ScoreDetailedForm.format_score_text(range_score_text, range_score);
				ScoreDetailedForm.format_score_text(total_score_text, total_score);
			} else {
				//Hide the view if we don't have all the necessary data.
				vis.visible = false;
			}
		});
	}
Exemplo n.º 36
0
        public AppModel()
        {
            // JPEG ファイルは DPI が異なる場合があります (既定では 96 だが、72 などもある)。
            // Image コントロールに直接読み込ませると、DPI によりサイズが変化してしまいます。
            ImageUrl
                .Subscribe(u =>
                {
                    var image = new BitmapImage(new Uri(u));

                    // ダウンロードの要否で分岐します。
                    if (image.IsDownloading)
                        image.DownloadCompleted += (o, e) => BitmapImage.Value = image;
                    else
                        BitmapImage.Value = image;
                });
            ImageUrl
                .Subscribe(_ => DetectAsync());

            IsImageEmpty = ImageUrl
                .Select(u => u == null)
                .ToReadOnlyReactiveProperty(true);
        }
Exemplo n.º 37
0
        public TodoItemViewModel(TodoItem todoItem)
        {
            this.Model = todoItem;
            this.Title = this.Model
                .ToReactivePropertyAsSynchronized(x => x.Title)
                .SetValidateAttribute(() => this.Title);

            this.Completed = this.Model
                .ToReactivePropertyAsSynchronized(x => x.Completed);

            this.ForegroundBrush = this.Model
                .ObserveProperty(x => x.Completed)
                .Select(x => x ? new SolidColorBrush(Colors.DarkGray) : new SolidColorBrush(Colors.Black))
                .Select(x => (Brush)x)
                .ToReadOnlyReactiveProperty();

            this.HasErrors = Observable.CombineLatest(
                this.Title.ObserveHasErrors,
                this.Completed.ObserveHasErrors)
                .Select(x => x.Any(y => y))
                .ToReadOnlyReactiveProperty();
        }
	void Awake () {
		rx_score.Subscribe((s)=>{
			if (s != null){
				date_time.text = s.time.date_recorded_local().ToString();
				score_text.text = s.final_score().ToString("0.00");
			}
		});
		
		rx_player_name = rx_score.SelectMany(s=>{
			if (s == null)
				return Observable.Never<String>();
			return s.rx_player_name.AsObservable();
		}).CombineLatest(LanguageController.controller.rx_load_text("score_default_name"), (name, default_name)=>{
			if (IsNullOrWhiteSpace(name))
				return default_name;
			return name;
		}).ToReadOnlyReactiveProperty<string>();
		
		rx_player_name.Subscribe(t=>{
			if (player_name != null)
				player_name.text = t;
		});
	}
	void Start(){
		if (ui_texts.Count == 0)
			ui_texts.AddRange(GetComponents<Text>());
		if (mesh_texts.Count == 0)
			mesh_texts.AddRange(GetComponents<TextMesh>());
		//Stopgap solution until I can get dependency injection working.
		if (controller == null){
			controller = LanguageController.controller;
		}
		rx_value = controller.rx_get_language_label(rx_language);
		sub = rx_value.Subscribe((t)=>{
			foreach(Text ui in ui_texts){
				if (ui != null){
					ui.text = t;
				}
			}
			foreach(TextMesh mesh in mesh_texts){
				if (mesh != null){
					mesh.text = t;
				}
			}
		});
	}
	void Start(){
		if (ui_texts.Count == 0)
			ui_texts.AddRange(GetComponents<Text>());
		if (mesh_texts.Count == 0)
			mesh_texts.AddRange(GetComponents<TextMesh>());
		//Stopgap solution until I can get dependency injection working.
		if (controller == null){
			controller = LanguageController.controller;
		}
		rx_value = controller.rx_load_text(rx_key);
		subscription = rx_value.Subscribe((t)=>{
			string full_text = prefix + t + suffix;
			foreach(Text ui in ui_texts){
				if (ui != null){
					ui.text = full_text;
				}
			}
			foreach(TextMesh mesh in mesh_texts){
				if (mesh != null){
					mesh.text = full_text;
				}
			}
		});
	}
Exemplo n.º 41
0
 public AppModel()
 {
     OcrLines = OcrResults
         .Select(ocr => ocr == null ? "" : string.Join("\r\n", ToLines(ocr)))
         .ToReadOnlyReactiveProperty();
 }
Exemplo n.º 42
0
        public MainViewModel()
        {
            var powerDistribution = ((App)App.Current).PowerDistribution;
            var powerDistributionLogger = ((App) Application.Current).PowerDistributionLogger;
            var viewSettings = ((App) Application.Current).ViewSettings;

            // View Settings
            this.PlotForeground = viewSettings
                .ObserveProperty(self => self.PlotStyle).Select(style => style.ObserveProperty(self => self.PlotForeground))
                .Switch()
                .Select(color => new SolidColorBrush(color))
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);
            this.PlotBackground = viewSettings
                .ObserveProperty(self => self.PlotStyle).Select(style => style.ObserveProperty(self => self.PlotBackground))
                .Switch()
                .Select(color => new SolidColorBrush(color))
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);

            this.CurrentSensors = powerDistribution.Sensors.ToReadOnlyReactiveCollection(sensor => new CurrentSensorViewModel(sensor)).AddTo(this.disposables);

            this.TotalCurrent = powerDistribution.ObserveProperty(self => self.TotalCurrent).ToReadOnlyReactiveProperty(mode:ReactivePropertyMode.RaiseLatestValueOnSubscribe)
                .AddTo(this.disposables);

            this.Capacity = powerDistribution.ObserveProperty(self => self.Capacity).ToReadOnlyReactiveProperty().AddTo(this.disposables);
            this.Usage = Observable.CombineLatest(
                    this.TotalCurrent,
                    this.Capacity,
                    (totalCurrent, capacity) => capacity > 0 ? totalCurrent / capacity : 0)
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);

            this.AlertState = Observable.CombineLatest(
                    powerDistribution.ObserveProperty(self => self.IsWarningCondition),
                    powerDistribution.ObserveProperty(self => self.IsCriticalCondition),
                    (isWarning, isCritical) => isCritical ? ErrorAlertState : (isWarning ? WarningAlertState : NormalAlertState))
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);


            this.CurrentPlotType = new ReactiveProperty<PlotType>().AddTo(this.disposables);
            this.IsLive = this.CurrentPlotType.Select(type => type == PlotType.Live).ToReadOnlyReactiveProperty().AddTo(this.disposables);
            this.IsCustom = this.CurrentPlotType.Select(type => type == PlotType.Custom).ToReadOnlyReactiveProperty().AddTo(this.disposables);
            this.IsHistroy = this.IsLive.Select(value => !value).ToReadOnlyReactiveProperty().AddTo(this.disposables);

            this.CurrentPlotModel = new OxyPlot.PlotModel()
            {
                Axes =
                {
                    new OxyPlot.Axes.LinearAxis() { Unit = "A", Position = OxyPlot.Axes.AxisPosition.Left, Minimum = 0 },
                    new OxyPlot.Axes.DateTimeAxis() { Unit = "Time", Position = OxyPlot.Axes.AxisPosition.Bottom },
                },
            };
            // Change plot model colors.
            viewSettings
                .ObserveProperty(self => self.PlotStyle).Select(style => style.ObserveProperty(self => self.PlotForeground))
                .Switch()
                .Subscribe(color_ =>
                {
                    var color = color_.ToOxyColor();
                    this.CurrentPlotModel.TextColor = color;
                    this.CurrentPlotModel.PlotAreaBorderColor = color;
                    foreach (var axis in this.CurrentPlotModel.Axes)
                    {
                        axis.MajorGridlineColor = color;
                        axis.MinorGridlineColor = color;
                        axis.TextColor = color;
                        axis.AxislineColor = color;
                        axis.TicklineColor = color;
                    }
                })
                .AddTo(this.disposables);
            var totalCurrentSeries = new OxyPlot.Series.LineSeries()
            {
                Title = "Total Current",
            };
            // Change plot series color.
            viewSettings
                .ObserveProperty(self => self.PlotStyle).Select(style => style.ObserveProperty(self => self.SeriesColor))
                .Switch()
                .Subscribe(color => totalCurrentSeries.Color = color.ToOxyColor())
                .AddTo(this.disposables);

            this.CurrentPlotModel.Series.Add(totalCurrentSeries);


            var currentHistory = this.TotalCurrent
                .Select(Value => new { Value, TimeStamp = DateTime.Now })
                .ToObservationHistory(Observable.Empty<Unit>(), pair => (DateTime.Now - pair.TimeStamp) >= TimeSpan.FromSeconds(60))
                .AddTo(this.disposables);

            var livePlotSource = currentHistory.HistoryChanged
                .Select(_ =>
                {
                    var history = currentHistory.GetHistory();
                    return history.Select(pair => new OxyPlot.DataPoint() {X = OxyPlot.Axes.DateTimeAxis.ToDouble(pair.TimeStamp), Y = pair.Value});
                });


            var historicPlotPeriods = HistoricPlotTypeConditions
                .Select(condition => this.CurrentPlotType
                    .Where(plotType => plotType == condition.PlotType)
                    .Select(_ => { var now_ = DateTimeOffset.Now; return new { From = condition.CalculateFrom(now_), To = condition.CalculateTo(now_)}; })
                )
                .ToArray();
            
            var now = DateTimeOffset.Now;
            var today = now.Subtract(now.TimeOfDay);
            this.PlotFromDate = new ReactiveProperty<DateTimeOffset>(today).AddTo(this.disposables);
            this.PlotToDate = new ReactiveProperty<DateTimeOffset>(today).AddTo(this.disposables);
            this.PlotFromTime = new ReactiveProperty<TimeSpan>(now.TimeOfDay).AddTo(this.disposables);
            this.PlotToTime = new ReactiveProperty<TimeSpan>(now.TimeOfDay).AddTo(this.disposables);
            this.UpdatePlotPeriodCommand = new ReactiveCommand().AddTo(this.disposables);
            var customPlotPeriod = this.UpdatePlotPeriodCommand
                .Select(_ => new {From = this.PlotFromDate.Value.Add(this.PlotFromTime.Value), To = this.PlotToDate.Value.Add(this.PlotToTime.Value)});

            var recordedPlotSource = Observable
                .Merge(historicPlotPeriods.Concat(new[] {customPlotPeriod}))
                .Select(period => powerDistributionLogger.GetPowerDistrubutionByPeriod(period.From, period.To))
                .Select(dataPoints => dataPoints.Select(pair => new OxyPlot.DataPoint() {X = OxyPlot.Axes.DateTimeAxis.ToDouble(pair.TimeStamp.LocalDateTime), Y = pair.Consumption}));

            var hasDataPointsSubject = new Subject<bool>().AddTo(this.disposables);
            var accumulatedCurrentSubject = new Subject<float>().AddTo(this.disposables);
            this.AccumulatedCurrent = accumulatedCurrentSubject.ToReadOnlyReactiveProperty().AddTo(this.disposables);
            this.IsLive
                .Select(isLive => isLive ? livePlotSource : recordedPlotSource)
                .Switch()
                .ObserveOnUIDispatcher()
                .Do(dataPointsEnumerable =>
                {
                    var dataPoints = dataPointsEnumerable.ToArray();
                    accumulatedCurrentSubject.OnNext(
                        (float)dataPoints.Pairwise().Sum(dataPoint => 
                            (dataPoint.OldItem.Y + dataPoint.NewItem.Y) * (OxyPlot.Axes.DateTimeAxis.ToDateTime(dataPoint.NewItem.X) - OxyPlot.Axes.DateTimeAxis.ToDateTime(dataPoint.OldItem.X)).TotalSeconds )
                                / 3600.0f);

                    hasDataPointsSubject.OnNext(dataPoints.Length > 0);
                    totalCurrentSeries.Points.Clear();
                    totalCurrentSeries.Points.AddRange(dataPoints);
                })
                .Do(_ => this.CurrentPlotModel.InvalidatePlot(true))
                .Subscribe()
                .AddTo(this.disposables);

            this.HasDataPoints = hasDataPointsSubject.ToReadOnlyReactiveProperty().AddTo(this.disposables);
        }
        public DevicePageViewModel(UnconnectedImbleDevice unconnectedDevice)
        {
            this.Device = Observable.FromAsync(token => unconnectedDevice.Connect(token))
                .CatchIgnore((Exception e) => { })
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);

            this.IsConnected = this.Device.Select(device => device != null).ToReadOnlyReactiveProperty().AddTo(this.disposables);

            this.DeviceStatus = this.Device
                .Where(device => device != null)
                .Select(device => device.ObserveProperty(self => self.Status))
                .Switch()
                .Do(value => Debug.WriteLine(value))
                .ObserveOnUIDispatcher()
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);

            this.ReceivedMessage = this.Device
                .Where(device => device != null)
                .Select(device => Observable.FromEventPattern<DataArrivedEventArgs>(handler => device.DataArrived += handler, handler => device.DataArrived -= handler))
                .Switch()
                .Select(args => new ReceivedMessageViewModel(args.EventArgs.Data, args.EventArgs.Timestamp))
                .OnErrorRetry()
                .ToReadOnlyReactiveProperty()
                .AddTo(this.disposables);

            var notBusyNotifier = new BooleanNotifier(false);
            
            this.Name = new ReactiveProperty<string>("Fuga")
                .SetValidateNotifyError(value => value != null && Encoding.UTF8.GetByteCount(value) < 12 ? null : "Input short message")
                .AddTo(this.disposables);

            this.CanSendCommand = Observable.CombineLatest(
                this.DeviceStatus.Select(status => status == ImbleDeviceStatus.Running),
                this.Name.ObserveHasErrors,
                notBusyNotifier.Do(value => Debug.WriteLine(value)),
                (isRunning, hasErrors, notBusy) => isRunning && !hasErrors && notBusy)
                .ToReadOnlyReactiveProperty().AddTo(this.disposables);
            notBusyNotifier.TurnOn();

            this.SendCommand = this.CanSendCommand.ToReactiveCommand().AddTo(this.disposables);
            this.SendCommand
                .Do(_ => notBusyNotifier.TurnOff())
                .Select(_ =>
                {
                    var data = Encoding.UTF8.GetBytes(this.Name.Value);
                        return Observable.FromAsync(token =>
                        {
                            using (var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
                            using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, timeoutTokenSource.Token))
                            {
                                return this.Device.Value.SendAsync(data, 0, data.Length, linkedTokenSource.Token);
                            }
                        })
                        .Finally(() => notBusyNotifier.TurnOn());
                })
                .Switch()
                .OnErrorRetry((Exception e) => Debug.WriteLine(e))
                .Subscribe()
                .AddTo(this.disposables);
        }
	void Start () {
		if (component != null)
			score = component.score_data;
		if (win == null)
			win = GameSettingsComponent.working_rules.win_condition;
			
		if (id_text != null || id_text_3d != null){
			rx_id_text = LanguageController.controller.rx_load_text("basket_single")
				.CombineLatest(rx_score.SelectMany(rx_score.SelectMany(s=>s.rx_id)), (text, id)=>{
					return text+" #"+id.ToString();
				}).ToReadOnlyReactiveProperty<string>();
			rx_id_text.Subscribe((text)=>{
				if (id_text != null)
					id_text.text = text;
				if (id_text_3d != null)
					id_text_3d.text = text;
			});
		}
		
		if (count != null || count_3d != null){
			rx_count_text = rx_score
				.SelectMany(s=>s.rx_count)
				.Select(value=>value.ToString())
				.ToReadOnlyReactiveProperty<string>();
			rx_count_text.Subscribe((text)=>{
				if (count != null)
					count.text = text;
				if (count_3d != null)
					count_3d.text = text;
			});
		}
		
		if (weight != null || weight_3d != null){
			rx_weight_text = rx_score
				.SelectMany(s=>s.rx_weight)
				.Select(value=>value.ToString("0.00"))
				.ToReadOnlyReactiveProperty<string>();
			rx_weight_text.Subscribe((text)=>{
				if (weight != null)
					weight.text = text;
				if (weight_3d != null)
					weight_3d.text = text;
			});
		}
		
		condition = rx_score.SelectMany(s=>{
			return s.rx_weight.CombineLatest(s.rx_overflow, (w,overflow)=>{
				return new UniRx.Tuple<float,bool>(w,overflow);
			});
		}).CombineLatest (rx_win, (tuple, wc) => {
			float w = tuple.Item1;
			bool overflow = tuple.Item2;
			if (overflow){
				return BasketCondition.Overflow;
			}
			if (wc.basket_weight.is_accept(w)){
				return BasketCondition.Accepted;
			} else {
				if (wc.basket_weight.is_over(w)){
					return BasketCondition.Overweight;
				} else {
					return BasketCondition.Underweight;
				}
			}
		}).ToReadOnlyReactiveProperty<BasketCondition>();
		
		rx_with_win = rx_score.CombineLatest(rx_win, (s, w)=>{
			return new UniRx.Tuple<BasketSingleScore, GameSettings.WinCondition>(s,w);
		});
		rx_with_win.Subscribe((tuple)=>{
			if (flat_score_text != null){
				ScoreDetailedForm.format_score_text(flat_score_text, tuple.Item2.evaluate_basket_flat(tuple.Item1));
			}
			if (range_score_text != null){
				ScoreDetailedForm.format_score_text(range_score_text, tuple.Item2.evaluate_basket_range(tuple.Item1));
			}
			if (total_score_text != null){
				ScoreDetailedForm.format_score_text(total_score_text, tuple.Item2.evaluate_basket(tuple.Item1));
			}
		});
		
		rx_tooltip_text = condition.Select(c=>language_keys[c]).ToReadOnlyReactiveProperty<string>();
		rx_tooltip_text.Subscribe((key)=>{
			if (tooltip != null){
				tooltip.key = key;
			}
		});
		
		rx_sprite = condition.Select(c=>sprites[c]).ToReadOnlyReactiveProperty<Sprite>();
		rx_sprite.Subscribe ((sprite) => {
			if (icon != null)
				icon.sprite = sprite;
			if (icon_3d != null)
				icon_3d.sprite = sprite;
		});
		
		if (opacity != null){
			opacity.opacity = off_opacity;
		}
	}