gpt4 book ai didi

c# - 为什么我不需要在这个冷的 Observable 上发布?

转载 作者:行者123 更新时间:2023-11-30 20:07:41 25 4
gpt4 key购买 nike

因为我感冒了Observable在这里,我多次订阅“分组”,为什么我不需要在这里发布?当我运行它时,我本以为它会产生不需要的结果,但令我惊讶的是它在有和没有 Publish 的情况下都能正常工作。这是为什么?

var subject = new List<string>
{
"test",
"test",
"hallo",
"test",
"hallo"
}.ToObservable();
subject
.GroupBy(x => x)
.SelectMany(grouped => grouped.Scan(0, (count, _) => ++count)
.Zip(grouped, (count, chars) => new { Chars = chars, Count = count }))
.Subscribe(result => Console.WriteLine("You typed {0} {1} times",
result.Chars, result.Count));

// I Would have expect that I need to use Publish like that
//subject
// .GroupBy(x => x)
// .SelectMany(grouped => grouped.Publish(sharedGroup =>
// sharedGroup.Scan(0, (count, _) => ++count)
// .Zip(sharedGroup, (count, chars) =>
// new { Chars = chars, Count = count })))
// .Subscribe(result => Console.WriteLine("You typed {0} {1} times",
// result.Chars, result.Count));

Console.ReadLine();

编辑

正如 Paul 所注意到的,因为我们订阅了底层的冷可观察对象两次,所以我们应该遍历序列两次。但是,我没有运气让这种效果可见。我尝试插入调试行,但例如这只打印一次“执行”。

var subject = new List<Func<string>>
{
() =>
{
Console.WriteLine("performing");
return "test";
},
() => "test",
() => "hallo",
() => "test",
() => "hallo"
}.ToObservable();


subject
.Select(x => x())
.GroupBy(x => x)
.SelectMany(grouped => grouped.Scan(0, (count, _) => ++count)
.Zip(grouped, (count, chars) => new { Chars = chars, Count = count }))
.Subscribe(result => Console.WriteLine("You typed {0} {1} times",
result.Chars, result.Count));

我想知道我们是否可以让效果可见,即我们正在处理一个冷可观察对象而不是使用 Publish() .在下一步中,我想看看如何 Publish() (见上文)使效果消失。

编辑 2

按照 Paul 的建议,我创建了一个自定义 IObservable<string>用于调试目的。但是,如果您在它的 Subscribe() 中设置断点方法,您会注意到它只会被击中一次

class Program
{
static void Main(string[] args)
{
var subject = new MyObservable();

subject
.GroupBy(x => x)
.SelectMany(grouped => grouped.Scan(0, (count, _) => ++count)
.Zip(grouped, (count, chars) => new { Chars = chars, Count = count }))
.Subscribe(result => Console.WriteLine("You typed {0} {1} times",
result.Chars, result.Count));

Console.ReadLine();
}
}

class MyObservable : IObservable<string>
{
public IDisposable Subscribe(IObserver<string> observer)
{
observer.OnNext("test");
observer.OnNext("test");
observer.OnNext("hallo");
observer.OnNext("test");
observer.OnNext("hallo");
return Disposable.Empty;
}
}

所以对我来说,这个问题仍然悬而未决。为什么我不需要 Publish这里很冷 Observable

最佳答案

您只使用一次基于列表的来源,因此您不会在那里看到重复的订阅效果。回答您的问题的关键是以下观察:

An IGroupedObservable<K, T> object flowing out of GroupBy by itself is a subject in disguise.

在内部,GroupBy 保留了一个 Dictionary >。每当有消息进来时,它都会使用相应的 key 发送到主题中。您订阅了分组对象两次,这是安全的,因为主题将生产者与消费者分离。

关于c# - 为什么我不需要在这个冷的 Observable 上发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107156/

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