Last active
July 18, 2024 08:18
-
-
Save marenovakovic/9466bfc1b765e06e1b3600efbc4da2f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.net.ConnectivityManager | |
import android.net.Network | |
import android.net.NetworkCapabilities | |
import android.net.NetworkRequest | |
import android.os.Bundle | |
import android.widget.TextView | |
import androidx.appcompat.app.AppCompatActivity | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.ViewModelProvider | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.FlowPreview | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.callbackFlow | |
import kotlinx.coroutines.flow.distinctUntilChanged | |
import kotlinx.coroutines.flow.flatMapConcat | |
import kotlinx.coroutines.flow.map | |
class MainActivity : AppCompatActivity() { | |
private val viewModel: NetworkStatusViewModel by lazy { | |
ViewModelProvider( | |
this, | |
object : ViewModelProvider.Factory { | |
override fun <T : ViewModel?> create(modelClass: Class<T>): T { | |
val networkStatusTracker = NetworkStatusTracker(this@MainActivity) | |
return NetworkStatusViewModel(networkStatusTracker) as T | |
} | |
}, | |
).get(NetworkStatusViewModel::class.java) | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
viewModel.state.observe(this) { state -> | |
findViewById<TextView>(R.id.textView).text = when (state) { | |
MyState.Fetched -> "Fetched" | |
MyState.Error -> "Error" | |
} | |
} | |
} | |
} | |
sealed class MyState { | |
object Fetched : MyState() | |
object Error : MyState() | |
} | |
class NetworkStatusViewModel( | |
networkStatusTracker: NetworkStatusTracker, | |
) : ViewModel() { | |
val state = | |
networkStatusTracker.networkStatus | |
.map( | |
onAvailable = { MyState.Fetched }, | |
onUnavailable = { MyState.Error }, | |
) | |
.asLiveData(Dispatchers.IO) | |
} | |
sealed class NetworkStatus { | |
object Available : NetworkStatus() | |
object Unavailable : NetworkStatus() | |
} | |
class NetworkStatusTracker(context: Context) { | |
private val connectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
val networkStatus = callbackFlow<NetworkStatus> { | |
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() { | |
override fun onUnavailable() { | |
println("onUnavailable") | |
offer(NetworkStatus.Unavailable) | |
} | |
override fun onAvailable(network: Network) { | |
println("onAvailable") | |
offer(NetworkStatus.Available) | |
} | |
override fun onLost(network: Network) { | |
println("onLost") | |
offer(NetworkStatus.Unavailable) | |
} | |
} | |
val request = NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) | |
.build() | |
connectivityManager.registerNetworkCallback(request, networkStatusCallback) | |
awaitClose { | |
connectivityManager.unregisterNetworkCallback(networkStatusCallback) | |
} | |
} | |
.distinctUntilChanged() | |
} | |
@FlowPreview | |
inline fun <Result> Flow<NetworkStatus>.map( | |
crossinline onUnavailable: suspend () -> Result, | |
crossinline onAvailable: suspend () -> Result, | |
): Flow<Result> = map { status -> | |
when (status) { | |
NetworkStatus.Unavailable -> onUnavailable() | |
NetworkStatus.Available -> onAvailable() | |
} | |
} | |
@FlowPreview | |
inline fun <Result> Flow<NetworkStatus>.flatMap( | |
crossinline onUnavailable: suspend () -> Flow<Result>, | |
crossinline onAvailable: suspend () -> Flow<Result>, | |
): Flow<Result> = flatMapConcat { status -> | |
when (status) { | |
NetworkStatus.Unavailable -> onUnavailable() | |
NetworkStatus.Available -> onAvailable() | |
} | |
} |
sralpert
commented
Nov 8, 2022
via email
I'll try to implement it again in a small project. If it recurs, I'll try to
email to you.
/steve
…On 11/8/2022 5:17 AM, Marko Novakovic wrote:
Re: marenovakovic/NetworkStatusTracker_full.kt ***@***.**** commented on
this gist.
--------------------------------------------------------------------------------
@sralpert <https://github.com/sralpert> sorry for late response. I can't
reproduce that, no issues when I try to implement it. best is to follow that
StackOverflow link
—
Reply to this email directly, view it on GitHub
<https://gist.github.com/9466bfc1b765e06e1b3600efbc4da2f8#gistcomment-4362166>
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABNZPETSS44647C3HJLZYWTWHISDLBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFQKSXMYLMOVS2I5DSOVS2I3TBNVS3W5DIOJSWCZC7OBQXE5DJMNUXAYLOORPWCY3UNF3GS5DZVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTAOBXGM4DGNBUU52HE2LHM5SXFJTDOJSWC5DF>.
You are receiving this email because you were mentioned.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
--
Steve Alpert
***@***.***
@Drjacky sorry. Where did you put the line connectivityManager.requestNetwork(request, networkStatusCallback, 1000)
? Thank you very much
...
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(request, callback)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
connectivityManager.requestNetwork(request, callback, 1000) //THISSSS
}
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}
.distinctUntilChanged()
Can have checking connection in kotlin multiplatform instead of seperate android and ios?
@hafiz013 sure you can.
there are libraries like:
https://github.com/jordond/connectivity
and
https://github.com/ln-12/multiplatform-connectivity-status
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment