簡體   English   中英

如何在 C# 中遍歷包含 IEnumerable 的 IObservable?

[英]How to loop through an IObservable containing an IEnumerable in C#?

我正在嘗試使用 C# 獲取配對藍牙設備的列表,使用的方法返回一個 IObservable 集合,其中包含 IEnumerable 對象,其中包含藍牙設備對象。 編譯器將分配此方法的返回類型的變量標記為IObservable<IEnumerable<IDevice>> 我正在嘗試從集合中訪問IDevice 該方法的文檔建議使用Subscribe()方法來遍歷集合,但我不知道此Subscribe()方法是否需要一些外部觸發器

List<string> devNames= new List<string>();
//I have tested the line below and it returns true so its not a permission issue
if (adapter.CanViewPairedDevices())
{
//here is my device collection variable
IObservable<IEnumerable<IDevice>> devices =adapter.GetConnectedDevices();
//here is how I try to get device names from the above collection
devices.Subscribe(deviceResult =>
       {
         foreach(var device in deviceResult){
                        devNames.Add(device.Name);
                                            }
       });
}
//devNames is still empty at this point

在方法調用結束時我的名稱列表為空, Subscribe是否需要某種觸發器? 是否有另一種迭代這種類型的方法會導致將名稱添加到列表中?

你想要的是這樣的:

IList<string> devNames =
    adapter
        .GetConnectedDevices()
        .SelectMany(devices => devices.Select(device => device.Name))
        .ToList()
        .Wait();

這將阻塞可能不需要的可觀察對象,因此您也可以等待此代碼並使其異步。 嘗試這個:

IList<string> devNames = await
    adapter
        .GetConnectedDevices()
        .SelectMany(devices => devices.Select(device => device.Name))
        .ToList();

您可以使用.Subscribe(...)但不會在訂閱中填充List<string> devNames 使用 Rx,就像我上面所說的,你最終會得到一個 observable 返回你的IList<string> ,所以在訂閱中你需要知道你想對列表做什么。 你沒有在問題中這么說,所以我無法回答。

devNames變量不是您的代碼片段的一部分,但我認為它是在執行此片段之前在某處聲明的。

Subscriptions的本質是它們是async的。
devices.Subscribe同步執行,但訂閱中的代碼:

foreach(var device in deviceResult)
{
    devNames.Add(device.Name);
}

將在稍后執行,這意味着devices.Subscribe之后的同步代碼可能無法看到結果。

您也可以在訂閱中添加引用devNames的邏輯來解決此問題。

List<string> bNames= new List<string>();
//I have tested the line below and it returns true so its not a permission issue
if (adapter.CanViewPairedDevices())
{
    //here is my device collection variable
    var devices =adapter.GetConnectedDevices();
    //here is how I try to get device names from the above collection
    devices.Subscribe(deviceResult =>
    {
        foreach(var device in deviceResult)
        {
            devNames.Add(device.Name);
        }
        // devNames is available here
    });
}

請嘗試一下,我認為它對您有用

 devNames = observable.Select(t => t.Name).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM