Skip to content

Commit

Permalink
修复EventLiveData无法在activity作用域下接收消息
Browse files Browse the repository at this point in the history
  • Loading branch information
hegaojian committed Jul 3, 2020
1 parent 27fd9b4 commit b62f243
Show file tree
Hide file tree
Showing 62 changed files with 533 additions and 474 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 12
versionName "1.1.3"
versionCode 14
versionName "1.1.4"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles 'consumer-rules.pro'
}
Expand Down Expand Up @@ -60,7 +60,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.3'//版本号 等于“me.hegj.JetpackMvvm:1.0.0”中的 1.0.0
publishVersion = '1.1.4'//版本号 等于“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
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import me.hgj.jetpackmvvm.network.manager.NetworkStateReceive
* 时间 : 2019/12/14
* 描述 : 对于写BaseApp,其实我是拒绝的,但是需要提供一个很有用的功能--在Activity/fragment中获取Application级别的ViewModel
* 所以才硬着头皮加的,如果你不想继承BaseApp,又想获取Application级别的ViewModel功能
* 那么你可以复制该类的代码到你的自定义Application中去,然后可以自己写获取Viewmodel的拓展函数即 :
* 那么你可以复制该类的代码到你的自定义Application中去,然后可以自己写获取ViewModel的拓展函数即 :
* GetViewModelExt类的getAppViewModel方法
*/
open class BaseApp : Application(), ViewModelStoreOwner {
Expand Down
6 changes: 2 additions & 4 deletions JetpackMvvm/src/main/java/me/hgj/jetpackmvvm/base/Ktx.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,12 @@ class Ktx : ContentProvider() {
private fun install(application: Application) {
app = application
mNetworkStateReceive = NetworkStateReceive()
app.registerReceiver(
mNetworkStateReceive,
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
)
app.registerReceiver( mNetworkStateReceive,IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
if (watchActivityLife) application.registerActivityLifecycleCallbacks(KtxLifeCycleCallBack())
if (watchAppLife) ProcessLifecycleOwner.get().lifecycle.addObserver(KtxAppLifeObserver)
}


override fun insert(uri: Uri, values: ContentValues?): Uri? = null

override fun query(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
/**
* 作者 : hegaojian
* 时间 : 2019/12/12
* 描述 : 包含Viewmodel 和Databind ViewModelActivity基类,把ViewModel 和Databind注入进来了
* 描述 : 包含ViewModel 和Databind ViewModelActivity基类,把ViewModel 和Databind注入进来了
* 需要使用Databind的清继承它
*/
abstract class BaseVmDbActivity<VM : BaseViewModel, DB : ViewDataBinding> : BaseVmActivity<VM>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ abstract class BaseVmFragment<VM : BaseViewModel> : Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isFirst = true
mViewModel = createViewModel()
initView(savedInstanceState)
createObserver()
Expand Down Expand Up @@ -130,8 +131,4 @@ abstract class BaseVmFragment<VM : BaseViewModel> : Fragment() {
dismissLoading()
})
}

override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ open class BaseViewModel : ViewModel() {
//显示加载框
val showDialog by lazy { EventLiveData<String>() }
//隐藏
val dismissDialog by lazy { EventLiveData<String>() }
val dismissDialog by lazy { EventLiveData<Boolean>() }
}

}
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
package me.hgj.jetpackmvvm.callback.livedata.event

import java.util.*

/**
* 配合 MutableLiveData & EventViewModel 的使用
* @author : hgj
* @date : 2020/6/8
* @date : 2020/7/3
*/
class Event<T>(private val content: T?) {

class Event<T>(content: T) {
private var content: T?
private var hasHandled = false
private var isDelaying = false
fun getContent(): T? {
if (hasHandled) {
return null
return if (!hasHandled) {
hasHandled = true
isDelaying = true
val timer = Timer()
val task: TimerTask = object : TimerTask() {
override fun run() {
content = null
isDelaying = false
}
}
timer.schedule(task, 1000)
content
} else if (isDelaying) {
content
} else {
null
}
hasHandled = true
return content
}

init {
this.content = content
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,20 @@ import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer

/**
* 专为 Event LiveData 改造的底层 LiveData 支持
* @author : hgj
* @date : 2020/6/8
* @date : 2020/7/3
*/

@SuppressLint("RestrictedApi")
abstract class EventBaseLiveData<T> {
private val mDataLock = Any()

private val mObservers =
SafeIterableMap<Observer<T>, ObserverWrapper>()

// how many observers are in active state
var mActiveCount = 0
private val mObservers = SafeIterableMap<Observer<T>, ObserverWrapper>()
private var mActiveCount = 0

@Volatile
private var mData: Any

// when setData is called, we set the pending data and actual data swap happens on the main
// thread
/* synthetic access */@Volatile
@Volatile
var mPendingData = NOT_SET
var version: Int
private set
Expand All @@ -41,7 +35,7 @@ abstract class EventBaseLiveData<T> {
newValue = mPendingData
mPendingData = NOT_SET
}
setValue(newValue as Event<T>)
setEvent(newValue as Event<T>)
}

/**
Expand All @@ -62,10 +56,7 @@ abstract class EventBaseLiveData<T> {
version = START_VERSION
}

private fun considerNotify(
observer: ObserverWrapper,
data: T?
) {
private fun considerNotify(observer: ObserverWrapper) {
if (!observer.mActive) {
return
}
Expand All @@ -82,14 +73,14 @@ abstract class EventBaseLiveData<T> {
return
}
observer.mLastVersion = version
val data = (mData as Event<T>).getContent()
if (data != null) {
observer.mEventObserver.onChanged(data)
}
}
/* synthetic access */
fun dispatchingValue(initiator: ObserverWrapper?) {
var initiator =
initiator

fun dispatchingValue(initiator: ObserverWrapper?) {
var initiator = initiator
if (mDispatchingValue) {
mDispatchInvalidated = true
return
Expand All @@ -98,19 +89,14 @@ abstract class EventBaseLiveData<T> {
do {
mDispatchInvalidated = false
if (initiator != null) {
considerNotify(initiator, null)
considerNotify(initiator)
initiator = null
} else {
val data =
(mData as Event<T>).getContent()
if (data != null) {
val iterator: Iterator<Map.Entry<Observer<T>, ObserverWrapper>> =
mObservers.iteratorWithAdditions()
while (iterator.hasNext()) {
considerNotify(iterator.next().value, data)
if (mDispatchInvalidated) {
break
}
val iterator: Iterator<Map.Entry<Observer<T>, ObserverWrapper>> = mObservers.iteratorWithAdditions()
while (iterator.hasNext()) {
considerNotify(iterator.next().value)
if (mDispatchInvalidated) {
break
}
}
}
Expand Down Expand Up @@ -155,19 +141,12 @@ abstract class EventBaseLiveData<T> {
@MainThread
fun observe(owner: LifecycleOwner, eventObserver: Observer<T>) {
assertMainThread("observe")
if (owner.lifecycle
.currentState == Lifecycle.State.DESTROYED
) {
if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
// ignore
return
}
val wrapper =
LifecycleBoundObserver(
owner,
eventObserver
)
val existing =
mObservers.putIfAbsent(eventObserver, wrapper)
val wrapper = LifecycleBoundObserver(owner, eventObserver)
val existing = mObservers.putIfAbsent(eventObserver, wrapper)
require(!(existing != null && !existing.isAttachedTo(owner))) {
("Cannot add the same observer"
+ " with different lifecycles")
Expand All @@ -180,7 +159,7 @@ abstract class EventBaseLiveData<T> {

/**
* Adds the given observer to the observers list. This call is similar to
* [ELiveData.observe] with a LifecycleOwner, which
* [EventBaseLiveData.observe] with a LifecycleOwner, which
* is always active. This means that the given observer will receive all events and will never
* be automatically removed. You should manually call [.removeObserver] to stop
* observing this LiveData.
Expand All @@ -196,12 +175,8 @@ abstract class EventBaseLiveData<T> {
@MainThread
fun observeForever(eventObserver: Observer<T>) {
assertMainThread("observeForever")
val wrapper =
AlwaysActiveObserver(
eventObserver
)
val existing =
mObservers.putIfAbsent(eventObserver, wrapper)
val wrapper = AlwaysActiveObserver(eventObserver)
val existing = mObservers.putIfAbsent(eventObserver, wrapper)
require(existing !is LifecycleBoundObserver) {
("Cannot add the same observer"
+ " with different lifecycles")
Expand All @@ -220,8 +195,7 @@ abstract class EventBaseLiveData<T> {
@MainThread
fun removeObserver(eventObserver: Observer<T>) {
assertMainThread("removeObserver")
val removed =
mObservers.remove(eventObserver) ?: return
val removed = mObservers.remove(eventObserver) ?: return
removed.detachObserver()
removed.activeStateChanged(false)
}
Expand Down Expand Up @@ -257,7 +231,7 @@ abstract class EventBaseLiveData<T> {
*
* @param value The new value
*/
protected open fun postValue(value: Event<T>) {
protected fun postEvent(value: Event<T>) {
var postTask: Boolean
synchronized(mDataLock) {
postTask = mPendingData === NOT_SET
Expand All @@ -274,12 +248,12 @@ abstract class EventBaseLiveData<T> {
*
*
* This method must be called from the main thread. If you need set a value from a background
* thread, you can use [&lt;][.setValue]
* thread, you can use [.postValue]
*
* @param value The new value
*/
@MainThread
protected open fun setValue(value: Event<T>) {
protected fun setEvent(value: Event<T>) {
assertMainThread("setValue")
version++
mData = value
Expand Down Expand Up @@ -341,23 +315,14 @@ abstract class EventBaseLiveData<T> {
return mActiveCount > 0
}

internal inner class LifecycleBoundObserver(
val mOwner: LifecycleOwner,
eventObserver: Observer<T>?
) : ObserverWrapper(eventObserver!!),
LifecycleEventObserver {
private inner class LifecycleBoundObserver(private val mOwner: LifecycleOwner, eventObserver: Observer<T>) : ObserverWrapper(eventObserver), LifecycleEventObserver {
override fun shouldBeActive(): Boolean {
return mOwner.lifecycle.currentState
.isAtLeast(Lifecycle.State.STARTED)
return mOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
}

override fun onStateChanged(
source: LifecycleOwner,
event: Lifecycle.Event
) {
if (mOwner.lifecycle
.currentState == Lifecycle.State.DESTROYED
) {
override fun onStateChanged(source: LifecycleOwner,
event: Lifecycle.Event) {
if (mOwner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
removeObserver(mEventObserver)
return
}
Expand All @@ -374,7 +339,8 @@ abstract class EventBaseLiveData<T> {

}

abstract inner class ObserverWrapper internal constructor(val mEventObserver: Observer<T>) {
abstract inner class ObserverWrapper internal constructor(eventObserver: Observer<T>) {
val mEventObserver: Observer<T> = eventObserver
var mActive = false
var mLastVersion = START_VERSION
abstract fun shouldBeActive(): Boolean
Expand Down Expand Up @@ -405,8 +371,7 @@ abstract class EventBaseLiveData<T> {

}

private inner class AlwaysActiveObserver internal constructor(eventObserver: Observer<T>?) :
ObserverWrapper(eventObserver!!) {
private inner class AlwaysActiveObserver internal constructor(eventObserver: Observer<T>) : ObserverWrapper(eventObserver) {
override fun shouldBeActive(): Boolean {
return true
}
Expand Down
Loading

0 comments on commit b62f243

Please sign in to comment.