Skip to content

Compose Integration

Thiago Santos edited this page Aug 18, 2024 · 4 revisions

Important

This module is a case of studies that shows how you can extend Kotlin Routing to your context.

Important

There are a lot of navigation libraries like Voyager, Jetpack Navigation, Decompose, etc. If your project is full Compose Multiplatform they are all you need for routing and navigating. Kotlin routing is general purpose and not a replacing to them.

Compose Multiplatform is a reality for kotlin developers and it is loved by them. Support to compose is required to any library that target kotlin frontend development.

So this module extend route handle to return a composable instead of just handle it.

sourceSets {
    commonMain.dependencies {
        implementation("dev.programadorthi.routing:compose:$version")
    }
}

Setup the composable

By the way that Compose works you need to use the Routing composable:

import dev.programadorthi.routing.compose.Routing
// ...

val router = routing {
    // ...
}

@Composable
fun App() {
    Routing(
        routing = router,
        startUri = "/start",
    )
}

Define composable handlers

import dev.programadorthi.routing.compose.composable
// ...

val router = routing {
    composable(path = "/start") {
        YourComposable()
    }
}

composable is a route handler on the hood and you can name it, change the route method, get call infos, and other behaviors as any route handler have.

Checkout Routing for more information.

Pop a composable

There is an extension function that need to be called to pop a composable. It works getting the previous route and invoking it.

Call the pop function

import dev.programadorthi.routing.compose.pop
// ...

router.pop()

Pop with result

import dev.programadorthi.routing.compose.composable
import dev.programadorthi.routing.compose.pop
import dev.programadorthi.routing.compose.popResult
// ...

val router = routing {
    composable(path = "/previous-route") {
        val value = LocalRouting.current.popResult<AnyValueInstance>()
        YouComposable(poppedValue = value)
    }
}

router.pop(result = AnyValueInstance)

Type-safe Composable

There is support to use type-safe with Composable too.

Create a annotated type

@Resource("/articles")
class Articles()

Install Resources

val router = routing {
    install(Resources)
}

Define composable handlers

val router = routing {
    // ...
    composable<Articles> {
        // ...
    }
}

Calling a composable resource

router.call(resource = Articles())

Checkout Type-safe Routing for more information.