Skip to content

Commit

Permalink
fix 请求网络时不显示loading问题
Browse files Browse the repository at this point in the history
  • Loading branch information
hegaojian committed Oct 12, 2020
1 parent b8b614b commit 34a9eb5
Show file tree
Hide file tree
Showing 15 changed files with 208 additions and 210 deletions.
6 changes: 3 additions & 3 deletions JetpackMvvm/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ android {
defaultConfig {
minSdkVersion 21
targetSdkVersion 29
versionCode 18
versionName "1.1.8"
versionCode 19
versionName "1.1.9"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
Expand Down Expand Up @@ -62,7 +62,7 @@ publish {
repoName = 'cxk'//仓库名字 这个可以随便起,比如我觉得我比较菜,所以我取了个蔡徐坤
groupId = 'me.hegj'//路径 名等于“me.hegj.JetpackMvvm:1.0.0”中的 me.hegj,你也可以写com.xxx
artifactId = 'JetpackMvvm'//项目名 等于“me.hegj.JetpackMvvm:1.0.0”中的 JetpackMvvm
publishVersion = '1.1.8'//版本号 等于“me.hegj.JetpackMvvm:1.0.0”中的 1.0.0
publishVersion = '1.1.9'//版本号 等于“me.hegj.JetpackMvvm:1.0.0”中的 1.0.0
desc = 'An Android Jetpack-MVVM framework,JetpackMvvm is nb?'//说明,不重要的东西,随便写
website = 'https://github.com/hegaojian/JetpackMvvm'//项目主页,用GitHub地址
licences = ['Apache-2.0']//协议
Expand Down
2 changes: 0 additions & 2 deletions JetpackMvvm/proguard-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

-optimizations !code/simplification/artithmetic,!field/*,!class/merging/*

-keep class me.hgj.jetpackmvvm.**{*;}

################common###############


Expand Down
1 change: 1 addition & 0 deletions JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/base/Ktx.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class Ktx : ContentProvider() {
mNetworkStateReceive,
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
)

if (watchActivityLife) application.registerActivityLifecycleCallbacks(KtxLifeCycleCallBack())
if (watchAppLife) ProcessLifecycleOwner.get().lifecycle.addObserver(KtxAppLifeObserver)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,29 +62,43 @@ abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {
private fun createViewModel(): VM {
return ViewModelProvider(this).get(getVmClazz(this))
}

/**
* 创建LiveData数据观察者
*/
abstract fun createObserver()

/**
* 注册 UI 事件
* 注册UI 事件
*/
private fun registerUiChange() {
//显示弹窗
mViewModel.loadingChange.showDialog.observe(this, Observer {
showLoading(
if (it.isEmpty()) {
"请求网络中..."
} else it
)
showLoading(it)
})
//关闭弹窗
mViewModel.loadingChange.dismissDialog.observe(this, Observer {
dismissLoading()
})
}

/**
* 将非该Activity绑定的ViewModel添加 loading回调 防止出现请求时不显示 loading 弹窗bug
* @param viewModels Array<out BaseViewModel>
*/
protected fun addLoadingObserve(vararg viewModels: BaseViewModel){
viewModels.forEach {viewModel ->
//显示弹窗
viewModel.loadingChange.showDialog.observe(this, Observer {
showLoading(it)
})
//关闭弹窗
viewModel.loadingChange.dismissDialog.observe(this, Observer {
dismissLoading()
})
}
}

fun userDataBinding(isUserDb: Boolean) {
this.isUserDb = isUserDb
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,10 @@ abstract class BaseVmFragment<VM : BaseViewModel> : Fragment() {
*/
open fun initData() {}


abstract fun showLoading(message: String = "请求网络中...")

abstract fun dismissLoading()


/**
* 注册 UI 事件
*/
Expand All @@ -134,4 +132,22 @@ abstract class BaseVmFragment<VM : BaseViewModel> : Fragment() {
dismissLoading()
})
}

/**
* 将非该Fragment绑定的ViewModel添加 loading回调 防止出现请求时不显示 loading 弹窗bug
* @param viewModels Array<out BaseViewModel>
*/
protected fun addLoadingObserve(vararg viewModels: BaseViewModel){
viewModels.forEach {viewModel ->
//显示弹窗
viewModel.loadingChange.showDialog.observe(viewLifecycleOwner, Observer {
showLoading(it)
})
//关闭弹窗
viewModel.loadingChange.dismissDialog.observe(viewLifecycleOwner, Observer {
dismissLoading()
})
}
}

}
Original file line number Diff line number Diff line change
@@ -1,83 +1,65 @@
package me.hgj.jetpackmvvm.callback.livedata

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import me.hgj.jetpackmvvm.ext.util.notNull
import java.util.*

/**
* 防止数据倒灌的LiveData
* @author : hgj
* @date : 2020/7/16
* 作者 : hegaojian
* 时间 : 2019/12/17
* 仅分发 owner observe 后 才新拿到的数据
* 可避免共享作用域 VM 下 liveData 被 observe 时旧数据倒灌的情况
*/

class UnPeekLiveData<T> : MutableLiveData<T>() {
private var isCleaning = false
private var hasHandled = true
private var isDelaying = false
private val mTimer = Timer()
private var mTask: TimerTask? = null
private var DELAY_TO_CLEAR_EVENT = 1000

override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, Observer {
if (isCleaning) {
hasHandled = true
isDelaying = false
isCleaning = false
return@Observer
}
if (!hasHandled) {
hasHandled = true
isDelaying = true
observer.onChanged(it)
} else if (isDelaying) {
observer.onChanged(it)
}
})
override fun observe(
owner: LifecycleOwner,
observer: Observer<in T>
) {
super.observe(owner, observer)
hook(observer)
}

override fun observeForever(observer: Observer<in T>) {
super.observeForever(Observer {
if (isCleaning) {
hasHandled = true
isDelaying = false
isCleaning = false
return@Observer
private fun hook(observer: Observer<in T>) {
val liveDataClass = LiveData::class.java
try {
//获取field private SafeIterableMap<Observer<T>, ObserverWrapper> mObservers
val mObservers = liveDataClass.getDeclaredField("mObservers")
mObservers.isAccessible = true
//获取SafeIterableMap集合mObservers
val observers = mObservers[this]
val observersClass: Class<*> = observers.javaClass
//获取SafeIterableMap的get(Object obj)方法
val methodGet =
observersClass.getDeclaredMethod("get", Any::class.java)
methodGet.isAccessible = true
//获取到observer在集合中对应的ObserverWrapper对象
val objectWrapperEntry = methodGet.invoke(observers, observer)
var objectWrapper: Any? = null
if (objectWrapperEntry is Map.Entry<*, *>) {
objectWrapper = objectWrapperEntry.value
}
if (!hasHandled) {
hasHandled = true
isDelaying = true
observer.onChanged(it)
} else if (isDelaying) {
observer.onChanged(it)
}
})
}

/**
* 重写的 setValue 方法
* @param value
*/
override fun setValue(value: T?) {
hasHandled = false
isDelaying = false
super.setValue(value)
mTask.notNull({
it.cancel()
mTimer.purge()
})
mTask = object : TimerTask() {
override fun run() {
clear()
if (objectWrapper == null) {
throw NullPointerException("ObserverWrapper can not be null")
}
//获取ObserverWrapper的Class对象 LifecycleBoundObserver extends ObserverWrapper
val wrapperClass: Class<*>? = objectWrapper.javaClass.superclass
//获取ObserverWrapper的field mLastVersion
val mLastVersion =
wrapperClass!!.getDeclaredField("mLastVersion")
mLastVersion.isAccessible = true
//获取liveData的field mVersion
val mVersion = liveDataClass.getDeclaredField("mVersion")
mVersion.isAccessible = true
val mV = mVersion[this]
//把当前ListData的mVersion赋值给 ObserverWrapper的field mLastVersion
mLastVersion[objectWrapper] = mV
mObservers.isAccessible = false
methodGet.isAccessible = false
mLastVersion.isAccessible = false
mVersion.isAccessible = false
} catch (e: Exception) {
e.printStackTrace()
}
mTimer.schedule(mTask, DELAY_TO_CLEAR_EVENT.toLong())
}

private fun clear() {
hasHandled = true
isDelaying = false
}
}
Loading

0 comments on commit 34a9eb5

Please sign in to comment.