RxJava for循环与异步方法?

时间:2016-12-03 09:16:59

标签: android rx-java

我正在学习如何在Android上使用RxJava。在我的项目中,我遇到一种情况,我从服务器获得public ActionResult getFilterExcel(List<FilterExcel> data) { System.Data.OleDb.OleDbConnection conn = null; try { string filename = ""; var oldfilename = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\datafiles\\lswm\\reports.xlsx"; filename = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\datafiles\\report\\report" + HttpContext.User.Identity.Name + ".xls"; System.IO.File.Copy(oldfilename, filename, true); conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + "; Extended Properties=\"Excel 12.0 Xml;HDR=NO\";"); conn.Open(); //return null; int i = 3; foreach (var item in data) { var strsql = "insert into [Report$C" + (i) + ":L" + (i) + "] (f1,f2,f3,f4,f5,f6,f7,f8,f9,f10)values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')"; var cmd = conn.CreateCommand(); cmd.CommandText = string.Format(strsql, item.ccrfNo, item.requestDate, item.requestedBy, item.title, item.changeImpact, item.plant, item.division, "", item.taskStatus, item.currentPhase ); var rowcount = cmd.ExecuteNonQuery(); i++; } } catch(Exception ex) { } finally { if (conn != null && conn.State == ConnectionState.Open) conn.Close(); } return File(Request.PhysicalApplicationPath + "\\datafiles\\report\\report" + HttpContext.User.Identity.Name + ".xls", "Application/MS-excel", "report" + HttpContext.User.Identity.Name + ".xls"); } 个项目,我需要在将响应返回给UI之前获取每个项目的详细信息。

问题是:我不确定如何Listsync内调用的API调用。我希望只有在for loop完成所有调用后才能将最终结果返回给用户界面。

任何提示非常感谢

示例代码:

foor loop

1 个答案:

答案 0 :(得分:6)

首先,由于您未订阅getDetailsForFavoriteItem(),因此未调用Observable中的API。

其次,最好flatMap将您的第一次回复转换为一个Observable<Favorite>,然后再次flatMap再次获取详细信息。像这样:

    Observable<List<Favorite>> result = ApiWrapper.getFavorites(userData)
            .flatMapIterable(favorites -> favorites)
            .flatMap(favorite -> getDetailsForFavoriteItem(favorite))
            .toList();

您甚至可以通过以下方式拨打并行电话来获取您的详细信息:

    Observable<List<Favorite>> result = getFavorites()
            .flatMapIterable(favorites -> favorites)
            .flatMap(favorite -> getDetailsForFavoriteItem(favorite)
                    .subscribeOn(Schedulers.io()), maxConcurrentCalls) // be sure to limit your maxConcurrentCalls or you might get OOM error
            .toList();