在ReactiveUI中获取源缓存的问题



我在订阅源缓存时有一个问题。让我来描述一下这个问题。假设我有一个Test Class

public class Test {
public bool feature1 {get; set;} = false;
public bool feature2 {get; set; } = false;
public string name;
public Test(string name){
this.name = name
}
}

我想看到测试类的属性发生变化,订阅者根据变化做出反应。但是在当前的实现中,只有当源缓存中元素的任何属性被更新时,才会收到通知。

class Notifier {
public SourceCache<Test, string> testClassNotifier = new SourceCache<Test, string>(x => x.Name);
public Notifier(){
Task.Run(() => 
{
this.AddOrUpdateSourceCache();
this.SubscribeTestObj1();
this.SubscribeTestObj2();
}).ConfigureAwait(false);
}

private AddOrUpdateSourceCache() 
{
List<Test> testListObj = new List<Test>() { new Test("test1"), new Test("test2") };
for (Test obj : testListObj) {
this.testClassNotifier.AddOrUpdate(obj); 
}
Task.Run(async () => {
for(int i = 0; i<2; i++) {
this.testListObj[i].feature1 = true;
await Task.Delay(4000).ConfigureAwait(false);
// I want here to my get the notification in change with intial values as well.
}
}).ConfiguareAwait(false);
}

private IObservable<Test,string> GetNotification(string name){
// which api should use here ?? Or any way I can use `WhenAny` here.
return this.testClassNotifier.Watch(name);
} 
private SubscribeTestObj1() {
this.GetNotification("test1").Subscribe(obj => // do something);
}
private SubscribeTestObj1() {
this.GetNotification("test2").Subscribe(obj => // do something);
}
}

一种解决方案:在Test类上实现INotifyPropertyChanged,使用AutoRefresh()

的例子:

public class Test : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
bool _feature1 = false;
public bool feature1 
{ 
get => _feature1; 
set 
{
_feature1 = value;
PropertyChanged?.Invoke(this, new(nameof(feature1)));       
}
}
// ... see the rest of the class in OP's question
}
测试:

var source = new SourceCache<Test, string>(x => x.name);
var a = new Test("a");
var b = new Test("b");
source
.Connect()
.AutoRefresh()
.Watch(b.name)
.Subscribe(change => Console.WriteLine($"Reason: <{change.Reason}> feature1: <{change.Current.feature1}>"));
source.AddOrUpdate(a);
source.AddOrUpdate(b);
b.feature1 = true;

输出:

Reason: <Add> feature1: <False>
Reason: <Refresh> feature1: <True>

相关内容

  • 没有找到相关文章

最新更新