I have a network call that gets LiveData. The Live...
# android
k
I have a network call that gets LiveData. The LiveData is observed with my Fragment's lifecycle owner. Does the coroutine call I make also need to be scoped to the fragment's lifecycleowner? In other words should I use one of these, or does it not matter?
Copy code
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch
or fragment.lifecycleScope.launch(context = Dispatchers.IO)
j
How does this exactly look like? Are you combining coroutines with livedata?
because I would do either the one or the other
Also, it would make sense to not make network calls from your presenter but from a place that is separated from your UI, like a ViewModel
In that case, the viewmodel can make the backend call, using viewModelScope and the fragment can observe that using livedata
but if for some reason you want to launch it from the fragment, I'd use something like this pseudo code:
Copy code
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
    showLoading()
    val result = service.doBackendCall()
    showResult(result)
}
What network library are you using?
if you use Retrofit and you use the retrofit suspend functions, you don't have to use the Dispatchers.IO as Retrofit will take care of threading so you don't have to
r
No , you should however do liveData.post() rather than liveData.value
Also you can use the liveData builder that has it's own coroutinescope... val results = liveData { emit(apiFetch)}
j
@rkeazor if you don't switch threads livedata.post is unnecessary
But to answer the question properly we'd anyway need more info
r
@Joost Klitsie Hes making a network call, it shouldnt be on the main thread .. That's a given. He should be using Dispatchers.IO... so I'm not entirely sure what you mean🤷‍♂️
j
@rkeazor Well as I said, if he uses retrofit with coroutines he doesn't need to use an io dispatcher as the retrofit library will take care of threading
Also why use livedata if you can solve it with coroutines
Also why use coroutines if he can solve it with livedata
It depends a bit on his architecture and libraries
r
Livedata and coroutines are different .If hes using Livedata that means that he has active observers somewhere in his UI listening for the change (i.e: databinding, fragment , or activity) listening for the change... I think post is better for all none synchronous events. But your should use a liveDataBuilder instead
j
well you are assuming he is doing it like that, but we don't know. Also post is for all non main thread -> main thread, so if you know you are on the main thread setValue is enough.
But for this, it sounds like a livedata builder might do the trick
but I don't know because there is not enough information
r
If your not observing a livedata. Why would you wrap data in it?