From bbe342ad219125512dccdbde3a03197285aa8b22 Mon Sep 17 00:00:00 2001 From: joffrey-bion Date: Wed, 10 Feb 2021 14:34:59 +0100 Subject: Properly start/stop sagas when using browser navigation Resolves: https://github.com/joffrey-bion/seven-wonders/issues/116 Related: https://github.com/joffrey-bion/seven-wonders/issues/114 Related: https://github.com/joffrey-bion/seven-wonders/issues/60 --- .../org/luxons/sevenwonders/ui/router/Router.kt | 24 ++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'sw-ui/src/main/kotlin/org/luxons') diff --git a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/router/Router.kt b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/router/Router.kt index b5dcb978..00f8cda5 100644 --- a/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/router/Router.kt +++ b/sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/router/Router.kt @@ -11,7 +11,13 @@ enum class Route(val path: String) { HOME("/"), GAME_BROWSER("/games"), LOBBY("/lobby"), - GAME("/game"), + GAME("/game"); + + companion object { + private val all = values().associateBy { it.path } + + fun from(path: String) = all.getValue(path) + } } data class Navigate(val route: Route) : RAction @@ -22,11 +28,21 @@ suspend fun SwSagaContext.routerSaga( ) { coroutineScope { window.location.hash = startRoute.path + launch { changeRouteOnNavigateAction() } var currentSaga: Job = launch { runRouteSaga(startRoute) } - onEach { + window.onhashchange = { event -> + val route = Route.from(event.newURL.substringAfter("#")) currentSaga.cancel() - window.location.hash = it.route.path - currentSaga = launch { runRouteSaga(it.route) } + currentSaga = this@coroutineScope.launch { + runRouteSaga(route) + } + Unit } } } + +suspend fun SwSagaContext.changeRouteOnNavigateAction() { + onEach { + window.location.hash = it.route.path + } +} -- cgit