Kotlin中的带有Dagger的物件(@Singleton)或物体

问题描述 投票:0回答:1

Singleton和几个LiveData用于观察和发布的最佳方法是什么?

Object:

object EventsObj {

    private val _actionLiveData = MutableLiveData<...>()
    val actionLiveData: LiveData<...> = _actionLiveData

    fun postActionEvent(value: ...) {
        _actionLiveData.postValue(value)
    }
    ... //few more LiveDatas following the same logic
}

或Dagger:

@Singleton
class EventsClass
@Inject constructor() {

    private val _actionLiveData = MutableLiveData<...>()
    val actionLiveData: LiveData<...> = _actionLiveData

    fun postActionEvent(value: ...) {
        _actionLiveData.postValue(value)
    }

    ... //few more LiveDatas following the same logic
}

用途:

@Inject
lateinit var eventsClass: EventsClass

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    eventsClass.actionLiveData.observe(this, ...)
    eventsClass.postActionEvent(...)

    EventsObj.actionLiveData.observe(this, ...)
    EventsObj.postActionEvent(...)
}
android kotlin singleton dagger-2
1个回答
0
投票

与Oject Kotlin合作将简化您的生活。它更容易调用。无需创建依赖关系并编写其他代码。

© www.soinside.com 2019 - 2024. All rights reserved.