c# - 如何在订阅开始之前延迟从 IObservable 获取元素?

标签 c# .net

我尝试在 Observable 序列开始之前插入 1 秒的延迟,但在调用 Subscribe 后立即发出第一条记录。在下面的示例中,我尝试通过传递 1s TimeSpan 来使用 RX 的 Take 运算符,并期望在调用 Subscribe< 时延迟接收数组中的第一个字符串...

public static void Main(string[] args)
{
    IEnumerable<string> e = new[] { "Hi", "There", "Bye" };
    IObservable<string> strings = e.ToObservable();

    IObservable<string> stringsTimed = strings.Take(TimeSpan.FromMilliseconds(1000));
    stringsTimed.Trace("string");

    Console.ReadLine();
}

public static IDisposable Trace<T>(this IObservable<T> source, string name)
{
    return source.Subscribe
    (
        onNext: t => Console.WriteLine($"{name} -> {t}"),
        onError: ex => Console.WriteLine($"{name} ERROR: {ex.Message}"),
        onCompleted: () => Console.WriteLine($"{name} END")
    );
}

但是当我运行程序时,“Hi”、“There”、“Bye”的结果立即打印在屏幕上,没有任何延迟,那么如何在接收第一个元素“Hi”之前添加 1 秒的延迟?

最佳答案

Take 不会延迟订阅。 TakeTimeSpan 重载设置了可观察对象在继续之前观察/获取记录的持续时间。

尝试下面的代码。如果您想使用帖子中的扩展方法(而不是下面的 RX Subscribe 扩展方法) - 在 DelaySubscription...

之后添加分号
string name = "Sample";
IEnumerable<string> e = new[] { "Hi", "There", "Bye" };

e.ToObservable()
    .DelaySubscription(TimeSpan.FromMilliseconds(1000))
    .Subscribe( onNext: t => Console.WriteLine($"{name} -> {t}"),
                onError: ex => Console.WriteLine($"{name} ERROR: {ex.Message}"),
                onCompleted: () => Console.WriteLine($"{name} END"));

关于c# - 如何在订阅开始之前延迟从 IObservable 获取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75398189/

相关文章:

c# - 需要澄清有关 Action<T>

Java 终结 : How can I free non-GC resource even if there's mistake

c# - RabbitMQ C# API : How to check if a binding exists?

c# - 无法在 Cisco WLC 上使用 SSH.NET 执行命令

c# - 是否有关于如何为 .net 应用程序本地化组织非字符串资源的指南?

c# - ASP.NET 动态修改控件树

c# - 当发送帐户使用双因素身份验证时,如何使用 Gmail 和 SmtpClient 发送电子邮件?

c# - 为什么不使用自定义字体? Xamarin.Forms.iOS

c# - "Found markup element with unexpected name"-- 重命名 Blazor Web 客户端后要做什么?

.net - 我如何将 const wchar_t* 转换为 System::String?