Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Model
public interface IData
{
IReadOnlyList<IDatum> DatumList { get; }
}
public interface IDatum
{
IReadOnlyList<int> Numbers { get; }
}
// ViewModel
public class ViewModel
{
private IDataRepository _repository;
public ReactiveCommand<int> GetDataSourceCommand { get; } = new ReactiveCommand<int>();
public ReactiveCommand ClearDataSourceCommand { get; } = new ReactiveCommand();
public IReadOnlyReactiveProperty<IData> Data { get; } // 書き込みが必要ないので ReadOnly へ
public IReadOnlyReactiveProperty<IEnumerable<int>> Numbers { get; } // 書き込みが必要ないので ReadOnly へ
public ViewModel()
{
//... DIとか ...
// 好みですが、こうも書けるという程度で
Data = Observable.Merge(
GetDataSourceCommand.Select(x => _repository.GetBy(id)),
ClearDataSourceCommand.Select(x => default(IData)))
.ToReadOnlyReactivePropertySlim();
// GetDataSourceCommand.Subscribe(id =>
// {
// Data.Value = _repository.GetBy(id);
// });
// ClearDataSourceCommand.Subscribe(_ =>
// {
// Data.Value = null;
// })
// IObservable(ReactiveProperty も IObservable を実装してます) を LINQ で加工して別の ReactiveProperty に代入するというパターンは大体 ToReadOnlyReactiveProperty/ToReactiveProperty で置き換え可能です
Numbers = Data.Select(x => x?.DatumList.SelectMany(y => y.Numbers)).ToReadOnlyReactivePropertySlim();
// Data.Subscribe(data => Numbers.Value = data?.DatumList.SelectMany(datum => datum.Numbers));
// Data に格納する必要がないなら 1 ステートメントにもできますが可読性と相談案件
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment