Skip to content

Instantly share code, notes, and snippets.

@gpeal
Last active August 28, 2018 17:54
Show Gist options
  • Save gpeal/87099abc09503f2e14a1c31b7bdcdc06 to your computer and use it in GitHub Desktop.
Save gpeal/87099abc09503f2e14a1c31b7bdcdc06 to your computer and use it in GitHub Desktop.
Airbnb MvRx Early Look
data class SimpleDemoState(val listing: Async<Listing> = Uninitialized)
class SimpleDemoViewModel(override val initialState: SimpleDemoState) : MvRxViewModel<SimpleDemoState>() {
init {
fetchListing()
}
private fun fetchListing() {
// This automatically fires off a request and maps its response to Async<Listing>
// which is a sealed class and can be: Unitialized, Loading, Success, and Fail.
// No need for separate success and failure handlers!
// This request is also lifecycle-aware. It will survive configuration changes and
// will never be delivered after onStop.
ListingRequest.forListingId(12345L).execute { copy(listing = it) }
}
}
class SimpleDemoFragment : MvRxFragment() {
// This will automatically subscribe to the ViewModel state and rebuild the epoxy models
// any time anything changes. Similar to how React's render method runs for every change of
// props or state.
private val viewModel by fragmentViewModel(SimpleDemoViewModel::class)
override fun EpoxyController.buildModels() {
val (state) = withState(viewModel)
if (state.listing is Loading) {
loader()
return
}
// These Epoxy models are not the views themself so calling buildModels is cheap. RecyclerView
// diffing will be automaticaly done and only the models that changed will re-render.
documentMarquee {
title(state.listing().name)
}
// Put the rest of your Epoxy models here...
}
override fun EpoxyController.buildFooter() = fixedActionFooter {
val (state) = withState(viewModel)
buttonLoading(state is Loading)
buttonText(state.listing().price)
buttonOnClickListener { _ -> }
}
}
@cesards
Copy link

cesards commented Aug 8, 2018

Is there any MvRx early version published anywhere?

@colintheshots
Copy link

Hopefully, we can see more soon. It would great to involve the Open Source community, so we can see if it's something we want to contribute to.

@arunkumar9t2
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment