Skip to content

Instantly share code, notes, and snippets.

@erdalkaymak
Created November 1, 2022 13:22
Show Gist options
  • Select an option

  • Save erdalkaymak/c42eed25d1f0ea4e48b4a5b2d65b1ab2 to your computer and use it in GitHub Desktop.

Select an option

Save erdalkaymak/c42eed25d1f0ea4e48b4a5b2d65b1ab2 to your computer and use it in GitHub Desktop.
/**
* Base class for [ViewModel] instances, all common processes will be handled based on this class.
*/
abstract class BaseViewModel : ViewModel() {
var showError = MutableLiveData<String?>()
override fun onCleared() {
LogUtils.d("$this")
super.onCleared()
}
/**
* Base method for Backend Api, returns the API response or error message.
*/
fun <T> makeNetworkRequest(
requestFunc: suspend () -> ResultWrapper<T>,
onSuccess: ((value: T) -> Unit)? = null,
onFail: ((value: IException) -> Unit)? = null
) {
viewModelScope.launch {
when (val response = requestFunc.invoke()) {
is ResultWrapper.Fail -> {
onFail?.invoke(response.value)
}
is ResultWrapper.Success -> {
onSuccess?.invoke(response.value)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment