在日常的Android
项目开发中,我们肯定会遇到需要检测用户设备的网络状态。防止用户没有网络的情况下,我们的应用没有提示。这里分享一个快速实现网络监听的开源库——ReactiveNetwork
ReactiveNetwork
ReactiveNetwork
是一个使用RxJava Observables
监听网络连接状态和Internet
连接的开源库。它是使用响应式编程方法重写的网络事件库的继承者。库支持新旧网络监控策略。最小 SDK 版本是9。
ReactiveNetwork引入
dependencies {
implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.8'
}
截止我发布博客,当前版本是3.0.8
。开源库版本最新版本请看开源库文档。
ReactiveNetwork的使用
观察网络连接:
ReactiveNetwork
.observeNetworkConnectivity(context)
.subscribeOn(Schedulers.io())
... // anything else what you can do with RxJava
.observeOn(AndroidSchedulers.mainThread())
.subscribe(connectivity -> {
// do something with connectivity
// you can call connectivity.state();
// connectivity.type(); or connectivity.toString();
});
持续观察互联网连接:
ReactiveNetwork
.observeInternetConnectivity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(isConnectedToInternet -> {
// do something with isConnectedToInternet value
});
与OkHttp一起集成
private Observable<Response> getResponse(String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
return Observable.create(emitter -> {
try {
Response response = client.newCall(request).execute();
emitter.onNext(response);
} catch (IOException exception) {
emitter.onError(exception);
} finally {
emitter.onComplete();
}
});
}
我们需要连接两个流:
ReactiveNetwork
.observeNetworkConnectivity(getApplicationContext())
.flatMap(connectivity -> {
if (connectivity.state() == NetworkInfo.State.CONNECTED) {
return getResponse("http://github.com");
}
return Observable.error(() -> new RuntimeException("not connected"));
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
response -> /* handle response here */,
throwable -> /* handle error here */)
);
与Retrofit一起集成
需要配置 Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
如你所见,我们需要RxJava2CallAdapterFactory在这里。接下来,我们需要使用 RxJavaSingle类型定义适当的接口:
public interface GitHubService {
@GET("users/{user}/repos")
Single<List<Repo>> listRepos(@Path("user") String user);
}
并实例化服务:
GitHubService service = retrofit.create(GitHubService.class);
接下来,每当我们连接到网络时,我们想调用使用 Retrofit 定义的端点。我们可以这样做:
ReactiveNetwork
.observeNetworkConnectivity(getApplicationContext())
.flatMapSingle(connectivity -> service.listRepos("pwittchen"))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
repos -> /* handle repos here */,
throwable -> /* handle error here */
);
ReactiveNetwork的混淆配置
-dontwarn com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork
-dontwarn io.reactivex.functions.Function
-dontwarn rx.internal.util.**
-dontwarn sun.misc.Unsafe