改造+ rxJava:如何实现迭代的N个请求? [英] Retrofit + rxJava: how to implement iterable N requests?

查看:501
本文介绍了改造+ rxJava:如何实现迭代的N个请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现以下问题一个问题:我做了获取所有活跃联赛的请求。然后,为他们每个人我需要另一个请求抢匹配。我认为这是可以实现使用flatMapIterable的解决方案,但是不知道怎么办。

I have a problem to implement following problem: I'm making a request that fetches all active leagues. Then, for each of them I need to make another request to grab the matches. I think it's possible to implement the solution using flatMapIterable, but don't know how.

现在我有以下改型接口:

For now I have following retrofit interfaces:

public interface LeaguesApi
{
    @GET("/api/get-leagues")
    Observable<ArrayList<League>> getLeagues(@Query("active_only") boolean activeOnly);
}

public interface LeagueApi
{
    @GET("/api/get-league-fixtures/{leagueId}")
    Observable<ArrayList<Match>> getMatchesPlayed(@Path("leagueId") int leagueId, @Query("played") boolean played);
}

请指教如何通过所有联赛,以便执行getMatchesPlayed为每个迭代。最好将没有拉姆达前pressions,因为我不是在我的项目中使用它们。

Please advise how to iterate through all leagues in order to perform getMatchesPlayed for each of them. Best would be without lambda expressions, since I'm not using them in my project.

推荐答案

我想改变这种API,所以它读取像这样,否则你会失去很多流的灵活性:

I'd change that API so it reads like this otherwise you lose a lot of the flexibility of streams:

public interface LeaguesApi
{
    @GET("/api/get-leagues")
    Observable<League> getLeagues(@Query("active_only") boolean activeOnly);
}

public interface LeagueApi
{
    @GET("/api/get-league-fixtures/{leagueId}")
    Observable<Match> getMatchesPlayed(@Path("leagueId") int leagueId, @Query("played") boolean played);
}

你能做到吗?

如果没有,那么要获得观测&LT; T&GT; 观测与LT; ArrayList的&LT; T&GT;&GT; 你这样做:

If not then to get Observable<T> from Observable<ArrayList<T>> you do:

observable.flatMapIterable(
    new Func1<ArrayList<T>, ArrayList<T>>() {
        @Override
        public ArrayList<T> call(ArrayList<T> list) {
            return list;
        }
    });

好得多,只是说 observable.flatMapIterable(X - &GT; X)。当然

要获得所有比赛场次的所有活动的联赛只是这样做:

To get all played matches for all active leagues just do this:

Observable<League> leagues= getLeagues(true);
Observable<Match> matches =
    leagues.flatMap( league -> getMatchesPlayed(league.leagueId, true));

或无的lambda(我希望你没有问那个)

or without lambdas (I wish you hadn't asked for that)

Observable<Match> matches = leagues.flatMap(
    new Func1<League, Observable<Match>> () {
        @Override
        public Observable<Match> call(League league) {
            return getMatchesPlayed(league.leagueId, true);
        }
    });

这篇关于改造+ rxJava:如何实现迭代的N个请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆