Is it okay to use LiveData objects inside a service?

Viewed 318

I am using Companion object in service to expose my LiveData to a fragment. Is this okay to use or will it cause me problems like memory leaks?

In my service:

  companion object {
    val timeLeftInSeconds = MutableLiveData<Long>(0)}

In my fragment:

 LockoutService.timeLeftInSeconds.observe(viewLifecycleOwner, Observer {...})
2 Answers

No it's fine because companion object is kinda like static fields, but I highly recommend to use a repository instead because it will increase you code readability and makes it more robust. Something like

object AppRepository{
    val timeLeftInSeconds = MutableLiveData<Long>(0)}
}

And in fragment

AppRepository.timeLeftInSeconds.observe(viewLifecycleOwner

No it's totally alright because companion objects are like static properties in java and are not bound to the class you define them in. Also you can put it in the same file, outside of your service

LockoutService.kt

val timeLeftInSeconds = MutableLiveData<Long>(0)}
class LockoutService {...}

And access it without mentioning the service name

Related