pwittchen / ReactiveNetwork
posted
Category: Other
Minimum SDK Level: Gingerbread (9 | 2.3.0 - 2.3.2)

Badge

View in Github Github project information
Starred: 0
Forks: 0
Watchers: 0
Open Issues: 0

Snapshot pictures

No snapshot for this library yet.

Description

ReactiveNetwork is an Android library listening network connection state and change of the WiFi signal strength with RxJava Observables. It's a successor of Network Events library rewritten with Reactive Programming approach.

Library is compatible with RxJava 1.0.+ and RxAndroid 1.0.+ and uses them under the hood.

min sdk version = 9

JavaDoc is available at: http://pwittchen.github.io/ReactiveNetwork/

Usage

Library has two RxJava Observables available in the public API:

Observable<ConnectivityStatus> observeConnectivity(final Context context)
Observable<List<ScanResult>> observeWifiAccessPoints(final Context context)

Observing connectivity

ConnectivityStatus can have one of the following values:

public enum ConnectivityStatus {
  WIFI_CONNECTED("connected to WiFi"),
  MOBILE_CONNECTED("connected to mobile network"),
  OFFLINE("offline");
  ...
}  

We can observe ConnectivityStatus with observeConnectivity(context) method in the following way:

new ReactiveNetwork().observeConnectivity(context)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    ... // anything else what you can do with RxJava
    .subscribe(new Action1<ConnectivityStatus>() {
      @Override public void call(ConnectivityStatus connectivityStatus) {
        // do something with connectivityStatus
      }
    });

We can react on a concrete status or statuses with the filter(...) method from RxJava, isEqualTo(final ConnectivityStatus... statuses) and isNotEqualTo(final ConnectivityStatus... statuses) methods located in ConnectivityStatus.

new ReactiveNetwork().observeConnectivity(context)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .filter(ConnectivityStatus.isEqualTo(ConnectivityStatus.WIFI_CONNECTED))
    .subscribe(new Action1<ConnectivityStatus>() {
      @Override public void call(ConnectivityStatus connectivityStatus) {
        // do something with connectivityStatus, which will be WIFI_CONNECTED
      }
    });

Observing WiFi Access Points

We can observe WiFi Access Points with observeWifiAccessPoints(context) method. Subscriber will be called everytime, when strength of the WiFi Access Points signal changes (it usually happens when user is moving around with a mobile device). We can do it in the following way:

new ReactiveNetwork().observeWifiAccessPoints(context)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    ... // anything else what you can do with RxJava
    .subscribe(new Action1<List<ScanResult>>() {
      @Override public void call(List<ScanResult> scanResults) {
        // do something with scanResults
      }
    });
2

See also