From 492ffb9c917ff52e447378db0fafa6849a29aca1 Mon Sep 17 00:00:00 2001 From: Nicole Date: Wed, 20 Sep 2023 15:02:30 +0300 Subject: [PATCH] Refactor ContributorsViewModel --- .../ivy/contributors/ContributorsViewModel.kt | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/screen-contributors/src/main/java/com/ivy/contributors/ContributorsViewModel.kt b/screen-contributors/src/main/java/com/ivy/contributors/ContributorsViewModel.kt index a902e1b39e..73ed3a90b3 100644 --- a/screen-contributors/src/main/java/com/ivy/contributors/ContributorsViewModel.kt +++ b/screen-contributors/src/main/java/com/ivy/contributors/ContributorsViewModel.kt @@ -3,6 +3,7 @@ package com.ivy.contributors import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.lifecycle.viewModelScope import com.ivy.core.ComposeViewModel import dagger.hilt.android.lifecycle.HiltViewModel @@ -15,11 +16,12 @@ class ContributorsViewModel @Inject constructor( private val contributorsDataSource: ContributorsDataSource ) : ComposeViewModel() { - private val contributors = mutableStateOf?>(null) private val contributorsState = mutableStateOf(ContributorsState.Loading) @Composable override fun uiState(): ContributorsState { + val contributors = remember { mutableStateOf?>(null) } + LaunchedEffect(Unit) { contributors.value = contributorsDataSource.fetchContributors()?.map { Contributor( @@ -30,10 +32,12 @@ class ContributorsViewModel @Inject constructor( ) } - val contributors = contributors.value + val contributorsList = contributors.value - if (contributors != null) { - contributorsState.value = ContributorsState.Success(contributors.toImmutableList()) + if (contributorsList != null) { + contributorsState.value = ContributorsState.Success( + contributorsList.toImmutableList() + ) } else { contributorsState.value = ContributorsState.Error("Error. Try again.") } @@ -49,8 +53,10 @@ class ContributorsViewModel @Inject constructor( } private fun onTryAgainButtonClicked() { + contributorsState.value = ContributorsState.Loading + viewModelScope.launch { - contributors.value = contributorsDataSource.fetchContributors()?.map { + val contributors = contributorsDataSource.fetchContributors()?.map { Contributor( name = it.login, photo = it.avatarUrl, @@ -58,6 +64,14 @@ class ContributorsViewModel @Inject constructor( link = it.link ) } + + if (contributors != null) { + contributorsState.value = ContributorsState.Success( + contributors.toImmutableList() + ) + } else { + contributorsState.value = ContributorsState.Error("Error. Try again.") + } } } } \ No newline at end of file