Skip to content

Commit

Permalink
Use SavedStateHandle in the ViewModel to get the nav args
Browse files Browse the repository at this point in the history
  • Loading branch information
cristan committed Oct 27, 2024
1 parent dc1f509 commit 6a80136
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ fun Navigation() {
else
slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.End)
}
) { backStackEntry ->
val locationCode = backStackEntry.arguments?.getString("locationCode")!!
) {
DetailScreen(
locationCode = locationCode,
onAlternativeClicked = { alternative ->
navController.navigate("detail/${alternative.locationCode}")
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,12 @@ import java.util.Locale

@Composable
fun DetailScreen(
locationCode: String,
viewModel: DetailsViewModel = koinViewModel(),
onAlternativeClicked: (LocationOverviewModel) -> Unit,
onBackClicked: () -> Unit
) {
LaunchedEffect(Unit) {
viewModel.setLocationCode(locationCode)
viewModel.screenLaunched()
}

val context = LocalContext.current
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package nl.ovfietsbeschikbaarheid.viewmodel

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
Expand All @@ -22,6 +23,7 @@ import java.time.ZoneId
private const val MIN_REFRESH_TIME = 350L

class DetailsViewModel(
savedStateHandle: SavedStateHandle,
private val client: KtorApiClient,
private val overviewRepository: OverviewRepository,
private val stationRepository: StationRepository
Expand All @@ -30,14 +32,12 @@ class DetailsViewModel(
private val _screenState = mutableStateOf<ScreenState<DetailsContent>>(ScreenState.Loading)
val screenState: State<ScreenState<DetailsContent>> = _screenState

private val _title = mutableStateOf("")
val title: State<String> = _title
private val overviewModel: LocationOverviewModel = overviewRepository.getAllLocations().find { it.locationCode == savedStateHandle["locationCode"] }!!

private lateinit var overviewModel: LocationOverviewModel
private val _title = mutableStateOf(overviewModel.title)
val title: State<String> = _title

fun setLocationCode(locationCode: String) {
overviewModel = overviewRepository.getAllLocations().find { it.locationCode == locationCode }!!
_title.value = overviewModel.title
fun screenLaunched() {
viewModelScope.launch {
doRefresh()
}
Expand Down

0 comments on commit 6a80136

Please sign in to comment.