简体   繁体   中英

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?

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. Its easier to call. There is no need to create dependencies and write additional code.

If you use Dagger, you will get more flexibility. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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