In The Name of Network
present
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:latest-version'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:latest-version'
implementation 'com.utsman.networkism:networkism:2.4.0'
result param | lollipop or newer | pre lollipop | value | desc |
---|---|---|---|---|
NetworkismResult.isConnected |
yes | yes | boolean |
the value of network available |
NetworkismResult.reason |
yes | yes | string |
the reason of connectivity |
NetworkismResult.Counter |
yes | no | object |
model of Kbps counter |
NetworkismResult.Counter.downKbps |
yes | no | Int |
current down stream bandwidth |
NetworkismResult.Counter.upKbps |
yes | no | Int |
current up stream bandwidth |
The Networkism use coroutine flow and cast to liveData with coroutineContext for lifecycle aware of activity or fragment
val networkism = Networkism.instance(context)
networkism.checkConnectionAsLiveData(lifecycleScope)
.observe(this, Observer { networkResult ->
if (networkResult.isConnected) {
// connected
} else {
// disconnected
}
})
// extend activity/fragment to `NetworkListener`
class MainActivity : AppCompatActivity(), NetworkismListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// init lifecycle scope from 'androidx.lifecycle:lifecycle-runtime-ktx'
val networkism = Networkism.instance(this)
networkism.setNetworkismListener(lifecycleScope, this)
}
override fun connectivityAvailable(counter: NetworkismResult.Counter?) {
// view for connection available
txt_log.text = "connect"
}
override fun connectivityLost() {
// view for disconnect
txt_log.text = "disconnect"
}
}
fun getUsers(page: Int = 1, networkism: Networkism) = viewModelScope.launch {
networkism.checkConnection()
.map { retrofit.getUser(page) }
.map { it.data.map { d -> d.lastName } }
.collect {
_users.postValue(it)
}
}
Checking connection of url
val networkism = Networkism.instance(context)
networkism.withConnectionBuilder {
okHttpClient = OkHttpClient()
url = "https://www.google.com"
}
See sample of dependencies injection with Dagger Hilt (sample)
Copyright 2020 Muhammad Utsman
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.