从收集元素中订阅计算值



我具有playerbuildings的重新分配。只有在生产珀斯或生产resourceId值会更改时才能订阅此集合?

我的意思是这样?

public void Sub()
{
      var collection = new ReactiveCollection<PlayerBuilding>();
      collection
         .where(x => x.ProducedResourceId == 1)
         .sum(y => y)
         .subscribe(_ => something);
}
public class PlayerBuilding
{
     public ReactiveProperty<SimpleRessourceEnum?> ProducedResourceId;
     public ReactiveProperty<int?> ProductionPerHour;
     public ReactiveProperty<int?> ProductionLimit;
}

更新

目的是将生产总和映射到TextValue。因此,我只有在ProductionPerhour会更改productuceSourceId = myResource或任何建筑物的生产的情况下才需要订阅信号。

public class ResourceItemScript : MonoBehaviour {
     private Text _valueText;
     private void Awake()
     {
          _valueText = transform.FindDeepChild("Text").GetComponent<Text>();
     }
     private void Start()
     {
     _productionService.GetProductionSumObservable(myResource)
          .SubscribeToText(_valueText);
     }
}

是反应性编程中的新事物,经过一些调查,我发现了一些解决方案。我创建了主题,这是我的建筑物集合和UI文本框之间的桥梁。我不认为这是最好的解决方案,但看起来它以某种方式起作用。所有提示和建议都非常欢迎。

public class ProductionSummaryObservable
{
    static Subject<Dictionary<SimpleRessourceEnum, int>> _subject;
    IBuildingsService _buildingService;
    IProductionService _productionService;
    private static readonly object lockObject = new object();
    protected Subject<Dictionary<SimpleRessourceEnum, int>> Subject
    {
        get
        {
            lock (lockObject)
            {
                if (_subject == null)
                {
                    _subject = new Subject<Dictionary<SimpleRessourceEnum, int>>();
                    var observables = _buildingService.GetProductionBuildings()
                        .Select(x => new { Level = x.Level, ProducedResource = x.ProducedResourceId })
                        .ToList();
                    Observable.Merge(observables
                        .Select(x => x.Level.AsObservable()))
                        .Subscribe(_ => _subject.OnNext(_productionService.GetProductionSummary()));
                    Observable.Merge(observables
                        .Select(x => x.ProducedResource.AsObservable()))
                        .Subscribe(_ => _subject.OnNext(_productionService.GetProductionSummary()));
                }
            }
            return _subject;
        }
    }
    public ProductionSummaryObservable(IBuildingsService buildingService, IProductionService productionService)
    {
        _buildingService = buildingService;
        _productionService = productionService;
    }
    public IObservable<int> ProductionSummaryByResourceObservable(SimpleRessourceEnum resource)
    {
        return Subject.Select(x => x.First(y => y.Key == resource).Value);
    }
}

相关内容

  • 没有找到相关文章

最新更新