https://kotlinlang.org logo
#compose
Title
# compose
i

Ian Warwick

12/31/2019, 11:21 AM
Hey folks, nearly happy new year here, really digging Compose, amazing work! I have been looking at a URI based navigation and wrote this front controller like
Router
pattern for a single activity approach using compose where you can specify URI routings to compositions - you can do something like this in your single activity
Copy code
class MainActivity : AppCompatActivity() {
    private val router = Router(this) {
        schemes("https", "http")
        hosts("<http://memset.com|memset.com>", "<http://www.memset.com|www.memset.com>")

        "/" composeWith { HomeScreenComposer() }
        "/cardeditor" composeWith { CardEditorScreenComposer(model(CardEditorViewModel::class)) }
        ".*" composeTo { Text("404 Not Found") }

    }.startAt("<https://memset.com/>")
}
Then later in your composition you can get at the router using an ambient
Copy code
val router = +ambient(ActiveRouter)
And navigate to another composition
Copy code
router.goto("<http://memset.com/anywhere>")
The problem is that if I get at the ambient inside an
onClick
listener since the listener is not
@Composable() () -> Unit
I get an error composition requires an active composition context Declaring the ambient ref outside the click listener works fine, before I was passing around
router: Router
to functions though learned about Ambient and thought why not try 😆 seems quite cool is it the right way to go for this sort of thing? apologies if the question is not relevant here, full source here:- https://github.com/fluxtah/memset
a

Adam Powell

12/31/2019, 2:56 PM
Ambients are a form of service locator with all of the tradeoffs involved. Any literature on service locators as dependencies will apply to ambients in terms of design
i

Ian Warwick

12/31/2019, 3:30 PM
ok cool thanks @Adam Powell! I think it fits then since the router is quite like a service for navigation scoped to the current compose screen, I just wonder if it was a design choice/constraint to not make
onClick
listeners
@Composable
or is it just an anti-pattern to reference with
+ambient(...)
in an
onClick
listener?
a

Adam Powell

12/31/2019, 3:31 PM
It's a design choice and it's going to be a compile error to try it very soon
👍 1
i

Ian Warwick

12/31/2019, 3:32 PM
aha 😄 awesome! definitely worth enforcing that there than at runtime, thanks