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