Search code examples
androidandroid-fragmentsandroid-serviceandroid-livedataandroid-lifecycle

Is it okay to use LiveData objects inside a service?


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 {...})

Solution

  • 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