Last active
January 12, 2021 14:30
-
-
Save DevSrSouza/329be1a69488767379bd9d257366e7b1 to your computer and use it in GitHub Desktop.
Simple routing system for Kotlin Multiplatform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.flow.StateFlow | |
import kotlin.reflect.KClass | |
interface Router<T : Any> { | |
// null if the backStack was cleared and the app was closed | |
val currentDirection: StateFlow<T?> | |
// will push the new direction | |
// if pop is not null, it will pop all previous direction down to the latest appearance of the pop kclass | |
fun push( | |
direction: T, | |
pop: KClass<out T>? = null, | |
inclusive: Boolean = false | |
) | |
fun pushPopLast(direction: T) | |
fun pop() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.flow.MutableStateFlow | |
import kotlinx.coroutines.flow.StateFlow | |
import kotlin.reflect.KClass | |
class SimpleRouter<T : Any>(initialRoot: T) : Router<T> { | |
private val backStack: MutableList<T> = mutableListOf<T>(initialRoot) | |
private val _currentDirection: MutableStateFlow<T?> = MutableStateFlow(initialRoot) | |
override val currentDirection: StateFlow<T?> = _currentDirection | |
override fun push( | |
direction: T, | |
pop: KClass<out T>?, | |
inclusive: Boolean | |
) { | |
if(pop != null) { | |
val last = backStack.findLast { pop.isInstance(it) } | |
if(last != null) { | |
val index = backStack.lastIndexOf(last) - if(inclusive) 0 else 1 | |
for(i in backStack.size-1 downTo index) { | |
backStack.removeLast() | |
} | |
} | |
} | |
pushDirection(direction) | |
} | |
override fun pushPopLast(direction: T) { | |
backStack.removeLast() | |
pushDirection(direction) | |
} | |
private fun pushDirection(direction: T) { | |
backStack.add(direction) | |
_currentDirection.value = direction | |
} | |
override fun pop() { | |
backStack.removeLastOrNull() | |
if(backStack.isEmpty()) { | |
_currentDirection.value = null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment