This my implementation which you can providing in application scope:
class NetworkStateHelper @Inject constructor(
private val context: Context
) {
private val cache: BehaviorSubject<Boolean> = BehaviorSubject.create()
private val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context?, intent: Intent?) {
cache.onNext(isOnlineOrConnecting())
}
}
init {
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(receiver, intentFilter)
cache.onNext(isOnlineOrConnecting())
}
fun subscribe(): Observable<Boolean> {
return cache
}
fun isOnlineOrConnecting(): Boolean {
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnectedOrConnecting
}
}
I used this rxjava and dagger2 libraies