0

If I return a request by liveData in a function and observe it in an activity to show the response, will my activity always observe liveData or only when the function is called?

viewModel:

fun blockContacts(contactList: List<Contact>): LiveData<Resource<Any>> {
    val live = MutableLiveData<Resource<Any>>(Resource.loading())
    viewModelScope.launch(ioDispatcher) {
        mutex.withLock {
        ...
        }
    }
    return live
}

Activity:

 viewModel.blockContacts(checkedList).observe(this) { res ->
             ...
         }
Hussein Yaqoobi
  • 442
  • 5
  • 20
  • What's happening in `withLock` and, also, why would you do this? – dominicoder May 04 '23 at 00:39
  • In the `withLock`, an HTTP request is sent to the server and the value of `livedata` is set with its response. I did this to lock the Thread, it is needed due to the structure of the program. – Hussein Yaqoobi May 04 '23 at 12:46
  • Sorry, when asking why would you do _this_ - _this_ refers to your question. Why would you create a brand new live data object and return it instead of making it a property of the view model, which is the standard practice? – dominicoder May 04 '23 at 14:58
  • Because I only display the value of `LiveData` when making a request and I don't want to observe it all the time so that the number of activity observers does not increase. – Hussein Yaqoobi May 05 '23 at 01:05
  • The number of activity observes should not increase. Presumably you have one ViewModel for one Activity, which will stop observing the LiveData when it is destroyed. – dominicoder May 05 '23 at 03:22
  • Yes, it is true, but I mean the number of observers in the same activity life cycle. I have more than 50 requests like this, I don't want my activity to observe 50 liveData during its life cycle, it affects the performance. – Hussein Yaqoobi May 05 '23 at 13:15
  • You shouldn't have "50 requests like this" - you should observe the LiveData object _once_ and, separately, you can make 50 request that update the _one_ live data. – dominicoder May 05 '23 at 15:00
  • So you mean that my method causes liveData to be observed throughout the activity lifecycle, not just when the function is called? – Hussein Yaqoobi May 05 '23 at 15:18
  • Correct - calling `observe` adds the lifecycle owner (i.e., activity) the the livedata's list of observers, which will exist until you explicitly remove it, or it removes itself when it is destroyed. Your current code is potentially more wasteful as you might be creating 50 live data objects all being observed by the activity even after the function returns. – dominicoder May 05 '23 at 15:40
  • I found a solution: https://stackoverflow.com/a/54648758/7687223 – Hussein Yaqoobi May 05 '23 at 18:37

0 Answers0