Created
August 3, 2022 20:04
-
-
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.
This file contains hidden or 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 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