위에서 설명드린 내용을 코드로 변환해 보면, 아래처럼 될 것 같습니다.
private fun check(name: String) {
nextButton.isEnabled = false
showProgressBar()
viewModel.fetchAllDataByName(name).observe { isSuccess ->
dismissProgressBar()
if (isSuccess) {
navigateToNextFragment()
return
}
handleFetchDataError()
}
}
private fun handleFetchDataError() {
Toast.makeText(context, "틀렸습니다.", Toast.LENGTH_SHORT).show()
nextButton.isEnabled = true
}
fun fetchAllDataByName(name: String): LiveData<Boolean> = liveData {
if (checkName(name)) {
getAllDataByName()
emit(true)
return@liveData
}
emit(false)
}
private suspend fun checkName(name: String) = withContext(Dispatcheres.IO) {
...
}
private suspend fun getAllDataByName(name: String)= withContext(Dispatcheres.IO) {
...
}
참고로 checkName, getAllData 둥의 함수는 state holder인 ViewModel의 역할과는 상관이 없으므로 UseCase/Interactor/Repository 등으로 옮겨서 처리하는 것이 좋습니다.
그리고 check, fetchAllData 등은 어떤 일을 할 수 있는지 알 수 있도록 명확한 이름을 사용하시면 더 좋을 것 같습니다. 예를 들면, checkUserName, fetchUsers 등 처럼요.