This library provides two Flow<T>
extension functions:
Flow<T>.observeIn(LifecycleOwner)
Flow<T>.observe(LifecycleOwner, suspend (T) -> Unit)
Those functions collect the flow and:
- Destroy its collection job on LifecycleOwner's
onStop()
. - Recreates its collection job on LifecycleOwner's
onStart()
.
The main motivation for this library is to have lifecycle-aware collectors much like those that can be launched with:
lifecycleScope.launchWhenStarted {
flow.collect { }
}
The issue with the above approach is that if our flow is a SharedFlow<T>
, paused collectors will still be subscribed collectors, so they will have no effect on SharedFlow
's SharingStarted.WhileSubscribed()
and SharedFlow<T>.subscriptionCount
configurations.
On project-level build.gradle
, add Jitpack repository:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
On app-level build.gradle
, add dependency:
dependencies {
implementation 'com.github.psteiger:flow-lifecycle-observer:0.1.2'
}
@AndroidEntryPoint
class NearbyUsersActivity : AppCompatActivity() {
private val viewModel: NearbyUsersViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
viewModel
.locations
.onEach { /* new locations received */ }
.observeIn(this)
viewModel
.users
.observe(this) {
/* new users received */
}
}
}