Skip to content

Commit

Permalink
feat: created BaseViewModel
Browse files Browse the repository at this point in the history
  • Loading branch information
Louiixx-h committed Oct 9, 2023
1 parent aee128e commit e67957e
Showing 1 changed file with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.luishenrique.cutecatsgallery.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

abstract class BaseViewModel : ViewModel() {
protected fun <T> request(
block: suspend () -> T,
onStartRequest: () -> Unit = {},
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit,
onFinally: () -> Unit = {}
) : Job {
return viewModelScope.launch {
onStartRequest.invoke()
runCatching {
val response = withContext(Dispatchers.IO) { block.invoke() }
onSuccess.invoke(response)
}.onFailure {
onError.invoke(it)
}
onFinally.invoke()
}
}
}

0 comments on commit e67957e

Please sign in to comment.