Use repeatOnLifecycle
This commit is contained in:
@@ -3,24 +3,19 @@ package gq.kirmanak.mealient.extensions
|
||||
import android.widget.Toast
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.FlowCollector
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
fun <T> Fragment.collectWhenViewResumed(
|
||||
flow: Flow<T>,
|
||||
collector: FlowCollector<T>,
|
||||
) = launchWhenViewResumed { flow.collect(collector) }
|
||||
|
||||
fun Fragment.launchWhenViewResumed(
|
||||
block: suspend CoroutineScope.() -> Unit,
|
||||
) = viewLifecycleOwner.lifecycleScope.launchWhenResumed(block)
|
||||
|
||||
fun <T> Flow<T>.launchIn(lifecycleOwner: LifecycleOwner) {
|
||||
launchIn(lifecycleOwner.lifecycleScope)
|
||||
fun <T> Fragment.collectWhenViewResumed(flow: Flow<T>, collector: FlowCollector<T>) {
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
flow.collect(collector)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun Fragment.showLongToast(@StringRes text: Int) = showLongToast(getString(text))
|
||||
|
||||
@@ -17,7 +17,6 @@ import gq.kirmanak.mealient.database.recipe.entity.RecipeSummaryEntity
|
||||
import gq.kirmanak.mealient.databinding.FragmentRecipesBinding
|
||||
import gq.kirmanak.mealient.datasource.NetworkError
|
||||
import gq.kirmanak.mealient.extensions.collectWhenViewResumed
|
||||
import gq.kirmanak.mealient.extensions.launchIn
|
||||
import gq.kirmanak.mealient.extensions.refreshRequestFlow
|
||||
import gq.kirmanak.mealient.extensions.showLongToast
|
||||
import gq.kirmanak.mealient.logging.Logger
|
||||
@@ -104,8 +103,8 @@ class RecipesFragment : Fragment(R.layout.fragment_recipes) {
|
||||
}
|
||||
|
||||
private fun <T : Any, VH : RecyclerView.ViewHolder> PagingDataAdapter<T, VH>.observeLoadStateChanges() {
|
||||
appendPaginationEnd().onEach { onPaginationEnd() }.launchIn(viewLifecycleOwner)
|
||||
refreshErrors().onEach { onLoadFailure(it) }.launchIn(viewLifecycleOwner)
|
||||
collectWhenViewResumed(appendPaginationEnd()) { onPaginationEnd() }
|
||||
collectWhenViewResumed(refreshErrors()) { onLoadFailure(it) }
|
||||
}
|
||||
|
||||
private fun onPaginationEnd() {
|
||||
|
||||
Reference in New Issue
Block a user