假设我有以下两个可观察的流
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
调用,await
从IObservable<IList<T>>
到IList<T>
。