在执行 API 调用之前检查 Observable 中的网络连接
Check for network connection in Observable before performing API calls
我正在尝试使用以下功能来检查网络连接
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);
是对接口 returns 可观察对象的调用,例如:
@GET("/user")
Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int page);
编辑:
有你的休息电话:
@GET("/user")
Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int page);
在初始化 restAdapter 的 class 中,实现 UserEntity:
public Observable<UserEntity> getUserEntity(String userId, int page){
return myRestAdapterInterface.UserEntity(userId, page);
}
让你的 observable 发出数据:
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(), ...))
我正在尝试使用以下功能来检查网络连接
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);
是对接口 returns 可观察对象的调用,例如:
@GET("/user")
Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int page);
编辑:
有你的休息电话:
@GET("/user")
Observable <UserEntity> UserEntity(@Query("user_ids") String user_id, @Query("page") int page);
在初始化 restAdapter 的 class 中,实现 UserEntity:
public Observable<UserEntity> getUserEntity(String userId, int page){
return myRestAdapterInterface.UserEntity(userId, page);
}
让你的 observable 发出数据:
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(), ...))