ViewModel (State Holder) is a class that is responsible for preparing and managing the data for UI element.
abstract class BaseViewModel extends LifeCycle {
final baseParams = BaseParams();
/// call http request, check if user connecting to internet before call the request
///
/// [result] is optional [LiveResult] params which control your [LiveResultBuilder]
/// [setLoading] is optional [Function] which control your ui-loader while request in-progress
/// [request] is a [Future] return type of [BaseResponse] called inside [callHttpRequest]
/// [callback] is a [Function] called after [request] fetched,
/// [callback] return nullable [X] result if [request] success else return "null"
Future<void> callHttpRequest<X>(
Future<BaseResponse<X>> Function() request, {
LiveResult<X>? result,
Function(bool value)? setLoading,
Function(X? result, bool success)? callback,
});
/// call http request with stream, this function used if your repository fetch data from multiple data-source (local and remote)
///
/// [setLoading] is optional [Function] which control your ui-loader while request in-progress
/// [result] is optional [LiveResult] params which control your [LiveResultBuilder]
/// [request] is a [Future] return type of [BaseResponse] called inside [callStreamRequest]
/// [callback] is a [Function] called after [request] fetched,
/// [callback] return nullable [X] result if [request] success else return "null"
Future<void> callStreamRequest<X>(
Stream<BaseResponse<X>> Function() request, {
LiveResult<X>? result,
Function(bool value)? setLoading,
Function(X? result, bool success)? callback,
});
/// show message through snackBar
void showUiMessage({required UiMessage uiMessage});
}
/// Controlled from [LifecycleOwner] widget
abstract class LifeCycle {
/// Called immediately after the widget is allocated in memory.
void onInit() {}
/// Called 1 frame after onInit(). It is the perfect place to enter navigation, events.
void onReady() {}
/// Called immediately before the widget is disposed.
void onDispose() {}
}
Implementing BaseViewModel:
class LoginViewModel extends BaseViewModel {
@override
void onInit() {
// called immediately after the widget is allocated in memory.
super.onInit();
}
@override
void onReady() {
// called 1 frame after onInit().
super.onReady();
}
@override
void onDispose() {
// called immediately before the widget is disposed
super.onDispose();
}
}