Refactor RecipesFragment

This commit extracts SwipeRefreshLayout extension to a
separate file. Additionally, it refactors RecipesFragment in
order to move all the logic to the ViewModel from the View.
This commit is contained in:
Kirill Kamakin
2021-11-27 00:22:52 +03:00
parent 897698ab02
commit cc5c9edb1f
5 changed files with 84 additions and 59 deletions

View File

@@ -0,0 +1,31 @@
package gq.kirmanak.mealient.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.asLiveData
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onClosed
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import timber.log.Timber
@ExperimentalCoroutinesApi
fun SwipeRefreshLayout.refreshesLiveData(): LiveData<Unit> {
val callbackFlow: Flow<Unit> = callbackFlow {
val listener = SwipeRefreshLayout.OnRefreshListener {
Timber.v("Refresh requested")
trySend(Unit)
.onFailure { Timber.e(it, "refreshesFlow: can't send refresh callback") }
.onClosed { Timber.e(it, "refreshesFlow: flow has been closed") }
}
Timber.v("Adding refresh request listener")
setOnRefreshListener(listener)
awaitClose {
Timber.v("Removing refresh request listener")
setOnRefreshListener(null)
}
}
return callbackFlow.asLiveData()
}