Skip to content

Instantly share code, notes, and snippets.

@MohammadRezaAlizadeh000
Created August 3, 2022 20:04
Show Gist options
  • Save MohammadRezaAlizadeh000/fba39fd838e0f634761502a342e563ec to your computer and use it in GitHub Desktop.
Save MohammadRezaAlizadeh000/fba39fd838e0f634761502a342e563ec to your computer and use it in GitHub Desktop.
To collect flow in fragment/activity you should write 3 line. I wrote extension that let you collect your flow in fragment/activity in 1 line.
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.launch
fun <T> Fragment.flowLife(flow: Flow<T>, collector: FlowCollector<T>) {
viewLifecycleOwner.lifecycleScope.launch {
lifecycleScope.launchWhenResumed {
flow.collect(collector)
}
}
}
fun <T> Fragment.suspendFlowLife(flow: suspend () -> Flow<T>, collector: FlowCollector<T>) {
viewLifecycleOwner.lifecycleScope.launch {
lifecycleScope.launchWhenResumed {
flow.invoke().collect(collector)
}
}
}
fun <T> AppCompatActivity.flowLife(flow: Flow<T>, collector: FlowCollector<T>) {
this.lifecycleScope.launch {
lifecycleScope.launchWhenResumed {
flow.collect(collector)
}
}
}
fun <T> AppCompatActivity.suspendFlowLife(flow: suspend () -> Flow<T>, collector: FlowCollector<T>) {
this.lifecycleScope.launch {
lifecycleScope.launchWhenResumed {
flow.invoke().collect(collector)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment