将依赖可观察的映射到子列表



假设我有以下两个可观察的流

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.

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

假设您的问题空间如下所示:

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>

相关内容

  • 没有找到相关文章

最新更新