Android Kaki

Build beautiful, usable products using required Components for Android.

Networking service utilizing callbackFlow and Jetpack Compose. | by Saqib | Could 2023

The way to view Community connection standing utilizing Kotlin Flows and present it inside Compose UI?

Community connection standing monitoring is a quite common use case, we need to present present community standing on person interface or to indicate retry mechanism if gadget is offline.

This story will present code examples of find out how to monitor and convert Community Connection callbacks to callbackFlow and observe it in UI layer to indicate updates inside Compose UI and eventually it would give helpful info Takeaways .


This story requires a primary understanding of the next substances

  • Kotlin Flows And callbackFlow
  • Dependency injection ( Dagger or Dagger Hilt)
  • Fundamental understanding of Jetpack Compose

What will we need to obtain?

We need to create a Community Connectivity Service to attain the next

  • Present display screen Community Standingon the gadget to see if the gadget is related to the Community.
  • Observe modifications to the Community state in actual time.
  • Use Jetpack Compose API to show offline standing inside Compose UI.

Go to Networking Providers.

Community Standing

Since we need to learn the Community Standing from the service. To show the Community Standing from the service, we are going to use a sealing layer containing that state info. See beneath NetworkStatus closed layer.

sealed class NetworkStatus {
object Unknown: NetworkStatus()
object Linked: NetworkStatus()
object Disconnected: NetworkStatus()

Community connection service

Let’s have a look at the code first.

NetworkConnectivityServiceImpl implementing an uncovered interface networkStatus EQUAL Move<NetworkStatus> .

Service in use callbackFlow , callbackFlow is a perfect alternative right here. Each time we need to convert any API callback to Kotlin Move callbackFlow is the reply. callbackFlow guarantee that the lambda remains to be lively in order that information may be despatched later within the callbacks. It additionally offers awaitClose block to unregister listeners when callbackFlow shut the door.

in lambda connectivityManager is subscribing to community state callbacks. In every callback technique, it sends a NetworkStatus use trySend . As talked about earlier than callbackFlow present awaitClose block to unsubscribe from community modifications. awaitClose can be known as when callbackFlow closed so we have to unsubscribe the listener.

flowOn(Dispatchers.IO) is to make sure that the decision networkStatus is fundamental security as a result of we are going to name it from UI class inside ViewModel.

distinctUntilChanged() be certain that it sends new worth solely when Community State modifications to keep away from sending pointless updates. In actual life circumstances it would normally occur that while you flip off Airplane mode you’re going to get a callback onAvailable twice, one for wifi and one for cell.

Must know extra about callbackFlow? I wrote an in depth story about callbackFlow take an instance of Firebase RealtimeDatabase callbacks and convert them to callbackFlow. If , you may learn from the hyperlink beneath.

Use Networking Service in ViewModel.

To offer present NetworkStatus for the person interface we are going to create a networkStatus property in ViewModel from there Compose UI will gather it.

Exposing a property in ViewModel will seem like beneath.

  • Move.StateIn Operator used to transform callbackFlow in StateFlow .
  • NetworkConnectivityService can be included as a dependency contained in the ViewModel constructor, I am utilizing HiltWhich Dependency Injector you need to use is as much as you.
  • initialValue inside Move.StateIn is ready Unknown as a result of initially once we load the UI we can’t know NetworkStatus and we do not need to present any message about UI defaults to any Linked or Disconnected.
  • Present viewModelScope will affiliate Move with the lifecycle of viewModelScope.
  • WhileSubscribed used to mechanically destroy upstream when no stream collector is on the market. WhileSubscribed(5000) will wait one other 5 minutes after the final receiver earlier than closing upstream, It can keep away from restarting the entire upstream unnecessarily, specifically throughout configuration modifications.

Gather community state inside Compose UI

On the UI we are going to present a notification when the gadget offline Use the snack bar. LaunchedEffect is your best option right here, I wrote a really detailed weblog put up about LaunchedEffect evaluate to rememberCoroutineScope discover and clarify When and The way to Use each APIs. I like to recommend you learn it, hyperlink is beneath.

Gather networkStatus inside Compose UI appears to be like like beneath.

  • collectAsStateWithLifecycle used to gather for networkStatus in Composable, It’s a lifecycle conscious API and the advisable strategy to gather Streams inside Compose.
  • LaunchedEffect used to make a droop perform snackbarHostState.showSnackbar("message") solely when networkStatus in Disconnected standing. LaunchedEffect launch the coroutine inside the scope of the composable the place it’s getting used and abort it when it leaves the element, so we need not fear concerning the auto-managed coroutine’s lifecycle.

carried away

  • callbackFlow particularly designed to transform any API callback into Kotlin Move.
  • Move.StateIn converts chilly present to sizzling present, on this instance it converts callbackFlow in StateFlow .
  • gather Move in Jetpack Compose lifecycle-aware through API collectAsStateWithLifecycle
  • WhileSubscribed(5000) wait 5 minutes earlier than beginning upstream once more if the stream does not have any observers, helpful in configuration modifications or heavy upstream and in addition in UI associated updates.
  • LaunchedEffect Results API is the advisable strategy to do it droop features as an impact of something taking place outdoors the composable vary and Community Connection modifications are an instance of these unintended effects occurring outdoors the composable vary .


That is it for now! Hope it helps… Any questions/options are welcome within the feedback.

👏 in case you prefer it and observe for extra tales 🙂

GitHub | LinkedIn | Twitter

John Wick: Chapter 4 (FREE) FULLMOVIE The Super Mario Bros Movie avatar 2 Where To Watch Creed 3 Free At Home Knock at the Cabin (2023) FullMovie Where To Watch Ant-Man 3 and the Wasp: Quantumania Cocaine Bear 2023 (FullMovie) Scream 6 Full Movie

Updated: May 11, 2023 — 11:30 am

Leave a Reply

Your email address will not be published. Required fields are marked * © 2023 Android kaki