Convert any callback API into a self cleaning Flow.

Kotlin Flows are amazing. Not only do they provide a non-blocking asynchronous way to deal with sequences of values, but they provide a clean and powerful API for dealing with event driven programming. Flows are easy to clean up to prevent leaks. They provide many functions and operators to deal with a myriad of scenarios and requirements. With an experimental function they are super easy to create around callback APIs.

The Jetpack team added [CoroutineScope](https://developer.android.com/topic/libraries/architecture/coroutines) support to the lifecycle in lifecycle-runtime-ktx version 2.2.0-alpha01. This allowed callers to launch coroutines in created, started, and resumed states that automatically cancelled them in the appropriate complementary state. For example the following Flow will be collected while the activity is started and stop when the onStop method is called:

lifecycleScope.launchWhenStarted {
  viewModel.getFlow().collect {
    // Do something with value
  }
}

Additionally they added a [viewModelScope](https://developer.android.com/topic/libraries/architecture/coroutines) in lifecycle-viewmodel-ktx version 2.1.0-beta01. This scope cancels coroutines when [ViewModel.onCleared()](https://developer.android.com/reference/androidx/lifecycle/ViewModel#onCleared()) is called. By properly using these scopes, we avoid having to remember to stop collecting from our flows, and avoid leaking long running processes when we no longer need them.

#kotlin #android #kotlin-coroutines #flow

Callback Flows in Android
21.95 GEEK