将依赖的observable映射到子列表

时间:2017-06-30 11:43:28

标签: c# system.reactive observable

说我有以下两个可观察的流

IObservable<LibraryView> GetLibrariesSource();
IObservable<FolderView> GetLibraryFolderSource(LibraryView library);

因此IObservable<FolderView>取决于LibraryView。这些视图也是扁平的,即它们没有导航属性。

如何将这两个流映射到IObservable<Library>流,其中Library包含Folder的列表

public class Library
{
    public List<Folder> Folders { get; set; }
}

假设我可以轻松地从LibraryView映射到Library,从FolderView映射到Folder

此外,我的最终目标是使用例如List<Library>来获取ForEachAsync。因此,可能没有必要创建IObservable<Library>

1 个答案:

答案 0 :(得分:2)

假设您的问题空间如下:

async Task Do()
{
    var libraryMapper = new Func<LibraryView, Library>(lv => /*implement me*/ new Library());
    var folderMapper = new Func<FolderView, Folder>(fv => /*implement me*/ new Folder());

    var librariesSource = new Func<IObservable<LibraryView>>(() => /*implement me*/ Observable.Empty<LibraryView>());
    var libraryFolderSource = new Func<LibraryView, IObservable<FolderView>>(lv => /*implement me*/ Observable.Empty<FolderView>());

}

public class Library 
{
    public List<Folder> Folders { get; set; }
}
public class Folder { }
public class LibraryView { }
public class FolderView { }

然后这样的事情将在Do()内发挥作用:

var libraryList = await librariesSource()
    .Select(lv => (LibraryView: lv, FolderViewObservable: libraryFolderSource(lv)))
    .SelectMany(async t => (LibraryView: t.LibraryView, FolderViews: await t.Item2.ToList()))
    .Select(t =>
    {
        var newLibrary = libraryMapper(t.LibraryView);
        newLibrary.Folders = t.FolderViews.Select(fv => folderMapper(fv)).ToList();
        return newLibrary;
    })
    .ToList();

使用Select来映射,SelectMany应用await来电,awaitIObservable<IList<T>>IList<T>