add LiveResouerHandler

androidx
Ztiany 5 years ago
parent 2fed64b3ef
commit e09842a9c9
  1. 28
      lib_base/src/main/java/com/android/base/app/aac/LiveResourceHandler.kt

@ -1,41 +1,25 @@
package com.android.base.app.aac
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.*
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.android.base.app.ui.LoadingView
import com.android.base.data.Resource
import timber.log.Timber
interface FragmentExtension {
/**用于创建 ViewModel 的 viewModelFactory*/
val viewModelFactory: ViewModelProvider.Factory
/**返回Fragment*/
val host: Fragment
interface LiveResourceHandler {
/**处理异常*/
fun handleError(throwable: Throwable)
}
inline fun <reified VM : ViewModel> FragmentExtension.injectViewModel(): Lazy<VM> {
return host.viewModels { viewModelFactory }
}
inline fun <reified VM : ViewModel> FragmentExtension.injectActivityViewModel(): Lazy<VM> {
return host.viewModels(
ownerProducer = { host.requireActivity() },
factoryProducer = { viewModelFactory })
}
fun <H, T> H.handleLiveResource(
liveData: LiveData<Resource<T>>,
forceLoading: Boolean = true,
onSuccess: (T?) -> Unit
) where H : FragmentExtension, H : LoadingView, H : LifecycleOwner {
) where H : LiveResourceHandler, H : LoadingView, H : LifecycleOwner {
liveData.observe(this, Observer {
when {
@ -63,7 +47,7 @@ fun <H, T> H.handleLiveResourceWithData(
forceLoading: Boolean = true,
onEmpty: (() -> Unit)? = null,
onSuccess: (T) -> Unit
) where H : FragmentExtension, H : LoadingView, H : LifecycleOwner {
) where H : LiveResourceHandler, H : LoadingView, H : LifecycleOwner {
liveData.observe(this, Observer {
when {
Loading…
Cancel
Save