Skip to content
This repository has been archived by the owner on Nov 5, 2024. It is now read-only.

Commit

Permalink
Refactor ContributorsViewModel
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolegeorgieva committed Sep 20, 2023
1 parent 332c696 commit 492ffb9
Showing 1 changed file with 19 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -15,11 +16,12 @@ class ContributorsViewModel @Inject constructor(
private val contributorsDataSource: ContributorsDataSource
) : ComposeViewModel<ContributorsState, ContributorsEvent>() {

private val contributors = mutableStateOf<List<Contributor>?>(null)
private val contributorsState = mutableStateOf<ContributorsState>(ContributorsState.Loading)

@Composable
override fun uiState(): ContributorsState {
val contributors = remember { mutableStateOf<List<Contributor>?>(null) }

LaunchedEffect(Unit) {
contributors.value = contributorsDataSource.fetchContributors()?.map {
Contributor(
Expand All @@ -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.")
}
Expand All @@ -49,15 +53,25 @@ 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,
contributions = it.contributions.toString(),
link = it.link
)
}

if (contributors != null) {
contributorsState.value = ContributorsState.Success(
contributors.toImmutableList()
)
} else {
contributorsState.value = ContributorsState.Error("Error. Try again.")
}
}
}
}

0 comments on commit 492ffb9

Please sign in to comment.