在执行API调用之前检查Observable中的网络连接

时间:2015-11-17 14:09:13

标签: android retrofit rx-android

我正在尝试使用以下功能来检查网络连接

 private boolean isThereInternetConnection() {
        boolean isConnected;
        ConnectivityManager connectivityManager =
                (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        isConnected = (networkInfo != null && networkInfo.isConnectedOrConnecting());

        return isConnected;
    } 

然后在我执行API调用之前调用它:

public Observable<UserEntity> userEntity(int page) {                                        return Observable.create(new Observable.OnSubscribe<UserEntity>() {
            @Override
            public void call(Subscriber<? super UserEntity> subscriber) {
                if (isThereInternetConnection()) {
                  // I want to return:
                return mUserApi.UserEntity(items,page);
                // in:
                  subscriber.onNext()
                } // otherwise return no internet connection message
            }
        });

请注意mUserApi.UserEntity(items,page);是对接口的调用,返回可观察对象,如:

@GET("/user")
    Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int  page);

1 个答案:

答案 0 :(得分:1)

编辑:

有你的休息电话:

@GET("/user")
Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int  page);

在初始化restAdapter的类中,实现UserEntity:

public Observable<UserEntity> getUserEntity(String userId, int page){
    return myRestAdapterInterface.UserEntity(userId, page);
}

制作会发出数据的可观察对象:

public Observable<UserEntity> userEntity(String userId, int page) {
    return getUserEntity(userId, page).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
//you can map, filter or do anything here   
}

然后订阅数据:

userEntity("id",5).subscribe(new Observer<UserEntity>() {
        @Override
        public void onCompleted() {
            //doSomething if u want
        }

        @Override
        public void onError(Throwable e) {
            //handle error
        }

        @Override
        public void onNext(List<UserEntity> userEntity) {
            //do something with the data
        }
    });

对于连接检查,请创建自己的客户端以进行改造:

public class ConnectivityAwareUrlClient implements Client {

private Context context;
private Client wrappedClient;

public ConnectivityAwareUrlClient(Context context, Client client) {
    this.context = context;
    this.wrappedClient = client;

}

@Override
public Response execute(Request request) throws IOException {
    if (!ConnectivityUtil.isConnected(context)) {
        throw RetrofitError.unexpectedError("No internet", new NoConnectivityException("No Internet"));
    } else {
        Response response = wrappedClient.execute(request);

        return response;
    }
}

}

在配置RestAdapter时使用它:

RestAdapter.Builder().setEndpoint(serverHost)
                 .setClient(new ConnectivityAwareUrlClient(new OkHttpClient(), ...))