Dependency injection with Koin
val dbModule = module {
single { Room.databaseBuilder(androidContext().applicationContext, AppDatabase::class.java, DB_NAME).build() }
single { get<AppDatabase>().surveyDao() }
}
Repository pattern
interface SurveyRepository {
suspend fun fetchNewSurvey(): Survey
suspend fun storeSurvey(survey: Survey)
suspend fun getPreviousSurveys(): List<PreviousSurvey>
}
Implementing usecases
class FetchSurveyUCImpl(private val surveyRepository: SurveyRepository) : FetchSurveyUC {
override suspend fun fetch() = surveyRepository.fetchNewSurvey()
}
Viewmodels with coroutine
class PreviousSurveyVM(
private val getPreviousSurveyUC: GetPreviousSurveyUC,
override val coroutineContext: CoroutineContext
) : ViewModel(), CoroutineScope {
private val _previousSurveyData = MutableLiveData<ModelResponse<List<PreviousSurvey>>> ()
val prevSurveyData: LiveData<ModelResponse<List<PreviousSurvey>>> = _previousSurveyData
fun get() {
launch {
_previousSurveyData.postValue(Loading())
try {
_previousSurveyData.postValue(SuccessResponse(body = getPreviousSurveyUC.get()))
} catch (e: Exception) {
_previousSurveyData.postValue(ErrorResponse(errorMessage = e.message))
e.printStackTrace()
}
}
}
}