I've inherited a Kotlin Android project from a former developer. He used suspend functions to handle, for example, network requests. An example of such a function might be this:
suspend fun performNetworkCall(param1: Long, param2: String): ResultOfCall
{
Do()
The()
Stuff()
return theResult
}
So far, so good. Now he has ViewModel
s for his fragments and he also has methods in these models that should call the above suspend function asynchronously and return some results. He does it like this:
sealed class LiveDataResult<out R>
{
data class Success<T>(val result: T) : LiveDataResult<T>()
data class Failure(val errorMessage: String) : LiveDataResult<Nothing>()
}
fun fetchSomeData(param1: Long, param2: String): LiveData<LiveDataResult<String>> = liveData {
val resultOfCall = performNetworkCall(param1, param2)
if (resultOfCall indicates success)
emit(LiveDataResult.Success("Yay!")
else
emit(LiveDataResult.Failure("Oh No!")
}
In his fragments he calls such methods like
viewModel.fetchSomeData(0, "Call Me").observe(viewLifecycleOwner) {
when (it)
{
is LiveDataResult.Success -> DoSomethingWith(it.result)
is LiveDataResult.Failure -> HandleThe(it.errorMessage)
}
}
I'm not very experienced in the entire observable/coroutine matter yet, so my questions on this approach are:
- Wouldn't that pile up a whole bunch of
LiveData
objects that won't get released due to the observer still being attached? - Is this a bad approach? Bad enough to refactor? And how should one refactor in case it should be refactored?