Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MVIJetpackComposeActivity : AppCompatActivity() {
lateinit var myViewModel: MVIJetpackComposeViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myViewModel = // factory to instantiate viewmodel
// just call setContent once
setContent {
CraneWrapper {
App(myViewModel)
}
}
}
@Composable
fun App(model: MVIJetpackComposeViewModel) {
MaterialTheme {
Scaffold(appBar = { MyAppBar() }) {
// observe the viewmodel here. compose will recompose when it changes.
val viewState = +observe(model.viewState)
viewState?.buildUI()
}
}
}
@Composable
fun MyAppBar() {
Row {
Text(text = "MVI Jetpack Compose App", style = +themeTextStyle { h4 })
}
}
// general purpose observe effect. this will likely be provided by LiveData. effect API for
// compose will also simplify soon.
fun <T> observe(data: LiveData<T>) = effectOf<T?> {
val result = +state<T?> { data.value }
val observer = +memo { Observer<T> { result.value = it } }
+onCommit(data) {
data.observeForever(observer)
onDispose { data.removeObserver(observer) }
}
result.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.