ReactiveConnectivity - a library for Listen Connectivity Change on Android
ReactiveConnectivity is an Android Library to Listening NetworkConnectivity with RxJava Observables, It's written with Reactive Programming Approach. Library supports both new and legacy network monitoring.
- Add the following to your project level
build.gradle
:
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
- Add this to your app
build.gradle
:
dependencies {
implementation 'com.github.amalhanaja:ReactiveConnectivity:1.0'
}
Add the ACCESS_NEWORK_STATE
permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- Getting Observbale:
private val observable by lazy {
ReactiveConnectivity.buildObserver(this)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
}
private var disposable: Disposable? = null // Lazy Initialization
- Initialize disposable on
onStart()
forActivity
OR
onResume()
forFragment
method :
disposable = observable.subscribe({ onChange ->
// TODO : DO SOMETHING ON NETWORK CHANGE
}, { error ->
// TODO : HANDLE ERROR HERE
})
- Dispose disposable on
onStop()
forActivity
OR
onPause()
forFragment
method to avoid Memory Leaks :
disposable?.dispose()
- Initialize Observer:
private val observer by lazy {
ReactiveConnectivity(
context = this,
onError = { it.printStackTrace() },
onChange = {
Toast.makeText(this, "MAIN ACTIVITY : ${it.name}", Toast.LENGTH_SHORT).show()
}
)
}
- Subscribe observer on
onStart()
forActivity
OR
onResume()
forFragment
method :
observer.subscribe()
- Dispose observer on
onStop()
forActivity
OR
onPause()
forFragment
method to avoid Memory Leaks :
disposable.dispose()
Copyright 2018 Alfian Akmal Hanantio
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Special thanks to pwittchen, ReactiveX, JetBrains and jitpack.io for their contributions to this project.