Created
February 16, 2022 06:41
-
-
Save rohitjakhar/44a170b049f7e40fdddf7b0516dcb076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rohit.healthOn.ui.homeScreen | |
import androidx.lifecycle.ViewModel | |
import androidx.lifecycle.viewModelScope | |
import com.rohit.healthOn.data.repo.AuthRepo | |
import com.rohit.healthOn.data.repo.SleepRepo | |
import com.rohit.healthOn.data.repo.WaterRepo | |
import com.rohit.healthOn.util.ERROR_TYPE | |
import com.rohit.healthOn.util.Resource | |
import dagger.hilt.android.lifecycle.HiltViewModel | |
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.flow.StateFlow | |
import kotlinx.coroutines.launch | |
import javax.inject.Inject | |
@HiltViewModel | |
class MainViewModel @Inject constructor( | |
private val waterRepo: WaterRepo, | |
private val sleepRepo: SleepRepo, | |
private val authRepo: AuthRepo | |
) : ViewModel() { | |
private val _events = MutableStateFlow<MainActivityScreenEvents>(MainActivityScreenEvents.Empty) | |
val events: StateFlow<MainActivityScreenEvents> = _events | |
private val _isLoading = MutableStateFlow(false) | |
val isLoading: StateFlow<Boolean> = _isLoading | |
init { | |
loadAllWaterLogs() | |
loadAllSleepLogs() | |
} | |
private fun loadAllWaterLogs() = viewModelScope.launch { | |
startLoading() | |
val resource = waterRepo.fetchAllWaterLogs() | |
stopLoading() | |
if (resource is Resource.Error) | |
handleError(resource) | |
} | |
private fun loadAllSleepLogs() = viewModelScope.launch { | |
startLoading() | |
val resource = sleepRepo.fetchAllSleepLogs() | |
stopLoading() | |
if (resource is Resource.Error) | |
handleError(resource) | |
} | |
private suspend fun stopLoading() { | |
_isLoading.emit(false) | |
} | |
private suspend fun startLoading() { | |
_isLoading.emit(true) | |
} | |
private suspend fun handleError(resource: Resource.Error<*>) { | |
val event = when (resource.errorType) { | |
ERROR_TYPE.NO_INTERNET -> MainActivityScreenEvents.ShowNoInternetDialog | |
ERROR_TYPE.UNKNOWN -> MainActivityScreenEvents.ShowToast(resource.message) | |
} | |
_events.emit(event) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment