如何用rx android做很多http请求?

时间:2016-12-20 13:19:48

标签: rx-java rx-android

在我的Android应用程序中我必须做很多http请求,所以我决定尝试使用rx java来做到这一点!

这就是我现在正在做的事情,但是有没有比使用for循环更好的解决方案? 有时我可能连续约有30个网址!

有人可以用正确的方式链接一个例子如何做到这一点吗?

public class MainActivity extends AppCompatActivity {

private Subscription subscription;
private TextView tvCard;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvCard = (TextView) findViewById(R.id.tvCards);
    tvCard.setMovementMethod(new ScrollingMovementMethod());

    for(int i =0;i<=20;i++){

        subscription = observableCardByUrl("https://blabla.com")                    
                .subscribeOn(Schedulers.io())    should be done
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Types>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, e.getMessage(), e);
                    }

                    @Override
                    public void onNext(Types types) {
                            tvCard.append(types.String + "\n");
                    }
                });
    }
}

public Observable<Types> observableCardByUrl(final String url) {
    return Observable.defer(new Func0<Observable<Types>>() {
        @Override
        public Observable<Types> call() {
            try {
                return Observable.just(getCard(url));
            } catch (IOException e) {
                return null;
            }
        }
    });
}


@Nullable
private Types getCard(String url) throws IOException {
    OkHttpClient okHttpClient = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url)
            .build();


    Response response = okHttpClient.newCall(request).execute();
    if (response.isSuccessful()) {
        Types types = new             Gson().fromJson(response.body().charStream(), Types.class);
        return types;
    }
    return null;
}

}

1 个答案:

答案 0 :(得分:1)

根据您提供的剪辑,最好使用

            Observable.range(0, 20)
            .flatMap(integer -> observableCardByUrl("https://blabla.com"))
            .subscribeOn(Schedulers.io())
            .observeOn(...)

如果您想要并行通话,我建议您使用Retrofit with rxjava adapter并查看this