gpt4 book ai didi

c# - 使主题同步不那么痛苦

转载 作者:行者123 更新时间:2023-11-30 23:33:49 25 4
gpt4 key购买 nike

我想同步访问 BehaviorSubject<T> ,所以我想使用 Subject.Synchronize .但是,我对这个界面有几个痛点,想知道我是否缺少一种更令人愉快的做事方式。

首先,我不得不同时存储原始主题和同步主题。这是因为我有时会使用 Value属性(property) BehaviorSubject<T> .也是因为Synchronize的返回值不是一次性的,所以我必须需要存储原始主题的实例才能正确处理它。

其次,Synchronize的返回值是ISubject<TSource, TResult> , 这与 ISubject<T> 不兼容.

因此我最终得到这样的代码:

public class SomeClass
{
private readonly BehaviorSubject<string> something;
private readonly ISubject<string, string> synchronizedSomething;

public SomeClass()
{
this.something = new BehaviorSubject<string>(null);

// having to provide the string type here twice is annoying
this.synchronizedSomething = Subject.Synchronize<string, string>(this.something);
}

// must remember to use synchronizedSomething here (I forgot and had to edit my question again, showing how easy it is to screw this up)
public IObservable<string> Something => this.synchronizedSomething.AsObservable();

// could be called from any thread
public void SomeMethod()
{
// do some work

// also must be careful to use synchronizedSomething here
this.synchronizedSomething.OnNext("some calculated value");
}

public void Dispose()
{
// synchronizedSomething is not disposable, so we must dispose the original subject
this.something.Dispose();
}
}

是否有我缺少的更清洁/更好的方法?需要明确的是,我希望能够做的是这样的事情(伪代码):

public class SomeClass
{
private readonly IBehaviorSubject<string> something;

public SomeClass()
{
this.something = new BehaviorSubject<string>(null).Synchronized();
}

public IObservable<string> Something => this.something.AsObservable();

// could be called from any thread
public void SomeMethod()
{
// do some work

this.something.OnNext("some calculated value");
}

public void Dispose()
{
this.something.Dispose();
}
}

最佳答案

我从您发布的代码示例中得到了一些注释

  1. IBehaviorSubject<string>不是 Rx.NET 中定义的类型。也许你的意思是ISubject<string>
  2. 你通过了null作为 BehaviorSubject<T> 的默认值,通常当我看到这个时,用户实际上只是想要 ReplaySubject<string>(1) .这取决于您是否有 Where(x=>x!=null)Skip(1)作为代码库中某处的补偿行为。
  3. 也许您想使用静态方法Subject.Synchronize(ISubject<T>)而不是扩展方法 .Synchronized()

这可能是上面示例代码的合适替代品。

public class SomeClass
{
//Exposed as ISubject as I can't see usage of `Value` and `TryGetValue` are not present.
private readonly ISubject<string> something;

public SomeClass()
{
var source = new BehaviorSubject<string>(null);
//Maybe this is actually what you want?
//var source = new ReplaySubject<string>(1);
this.something = Subject.Synchronize(source);
}

public IObservable<string> Something => this.something.AsObservable();

// could be called from any thread
public void SomeMethod()
{
// do some work

this.something.OnNext("some calculated value");
}
}

关于c# - 使主题同步不那么痛苦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com