简体   繁体   English

使用 Dagger (@Singleton) 或 Object 在 Kotlin 中单例

[英]Singleton in Kotlin with Dagger (@Singleton) or Object

What's the best approach for having a Singleton with a few LiveData for observing and posting?使用带有一些LiveDataSingleton进行观察和发布的最佳方法是什么?

Object:目的:

object EventsObj {

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

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

or 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
}

Use:用:

@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(...)
}

Working with Oject Kotlin will simplify your life.与 Oject Kotlin 合作将简化您的生活。 Its easier to call.打电话更方便。 There is no need to create dependencies and write additional code.无需创建依赖项和编写额外的代码。

If you use Dagger, you will get more flexibility.如果您使用 Dagger,您将获得更大的灵活性。 Because You can replace the code for testing.因为您可以替换代码进行测试。 And in the case when you will need to replace one implementation with another, you will have to change the code only in one place.如果您需要将一种实现替换为另一种实现,则只需在一处更改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM