所有并行HTTP请求完成后如何调用方法?

时间:2018-03-23 22:46:23

标签: android asynchronous retrofit2 rx-java2 rx-android

我需要获取类别,然后获取该类别的通道,最后在从服务器检索所有类别及其通道时调用方法。我想我需要使用RxJava,但我找不到类似的实现。 (最好不使用lambda / retrolambda表达式。)

@GET("/api/{categoryId})
Call<Category> getCategory(@Path("categoryId") String categoryId)


private void getCategories() {
    for (Tab t : tabs) {
        Call<Category> getCategory = videoAPI.getCategory(t.getId());
        getCategory.enqueue(new Callback<Category>() {
            @Override
            public void onResponse(Call<Category> call, Response<Category> response) {
                Category cat = response.body();
                categories.add(cat);
                // I will call the getChannels(String categoryId) method here, 
                // however I think implementing RxJava would be much better.
            }

            @Override
            public void onFailure(Call<Category> call, Throwable t) {
                Log.i(TAG, "failure: " + t.getLocalizedMessage());
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

你可以用

做到这一点
public class Main extends Thread{

    public static void main(String[] args) {

        Thread[] threads = new Thread[1000];

        Adder adder = new Adder();

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new ThreadAddSync(adder));
            threads[i].start();

        }

        System.out.println("----- " + adder.count);
    }
}

public class ThreadAddSync implements Runnable{

    Adder add;

    public ThreadAddSync(Adder add){
        this.add = add;
    }

    @Override
    public void run() {
        synchronized(add){
            add.add();
        }
    }
}

public class Adder {

    int count = 0;

    public void add(){
        count += 1;
    }
}

现在您的请求必须是Observable类型

Observable
    .fromArray(/*your list of observables go here, make sure that within flatMap you get as type Observable<T>, not Observable<List<T>>*/)
    .flatMap(/*here you subscribe every item to a different thread, so they're parallel requests: subscribeOn(Schedulers.computation())*/)
    .subscribe (/*each request*/,/*error*/,/*completed all requests*/)

Java

中的示例代码
@GET("/api/{categoryId}) 
Observable<Category> getCategory(@Path("categoryId") String categoryId) 

或者如果你正在使用 Kotlin

// Setup a list of observables
List<Observable<Category>> parallelRequests = new ArrayList<>();
for (Tab t : tabs) {
    parallelRequests.add(videoAPI.getCategory(t.getId()));
}
Observable[] array = new Observable[parallelRequests.size()];

// Convert the list to array
parallelRequests.toArray(array);

Observable
        .fromArray(array)
        .flatMap(observable -> observable.subscribeOn(Schedulers.computation()))
        .subscribe(o -> {
            // each request is fulfilled
        }, Throwable::printStackTrace, () -> finishFunctionHere());
相关问题