Skip to content

Instantly share code, notes, and snippets.

@gpeal
Last active April 27, 2021 01:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpeal/5bed618a843d4d71bb1518fa8317c5df to your computer and use it in GitHub Desktop.
Save gpeal/5bed618a843d4d71bb1518fa8317c5df to your computer and use it in GitHub Desktop.
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.AmbientContext
import androidx.compose.ui.platform.AmbientLifecycleOwner
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.airbnb.mvrx.*
@Composable
fun <VM : MavericksViewModel<S>, S : MavericksState> VM.collectState(): S {
val state by stateFlow.collectAsState(initial = withState(this) { it })
return state
}
@Composable
inline fun <reified VM : MavericksViewModel<S>, reified S : MavericksState> mavericksViewModel(): VM {
val viewModelClass = VM::class
val viewModelContext = when (val lifecycleOwner = LocalLifecycleOwner.current) {
is Fragment -> {
val activity = lifecycleOwner.requireActivity()
val args = lifecycleOwner.arguments?.get(Mavericks.KEY_ARG)
FragmentViewModelContext(activity, args, lifecycleOwner)
}
is FragmentActivity -> {
val args = lifecycleOwner.intent.extras?.get(Mavericks.KEY_ARG)
ActivityViewModelContext(lifecycleOwner, args)
}
else -> error("Unknown LifecycleOwner ${lifecycleOwner::class.simpleName}. Must be Fragment or Activity for now.")
}
val activity = LocalContext.current as? FragmentActivity ?: error("Composable is not hosted in a FragmentActivity")
return remember(viewModelClass, activity) {
val keyFactory = { viewModelClass.java.name }
MavericksViewModelProvider.get(
viewModelClass = viewModelClass.java,
stateClass = S::class.java,
viewModelContext = viewModelContext,
key = keyFactory()
)
}
}
@Composable
fun MyComposable() {
val viewModel: MyViewModel = mavericksViewModel()
val state = viewModel.collectAsState()
AnotherComposable(
state.value,
onClick = viewModel.onClick()
)
}
@tinder-christopherperry
Copy link

tinder-christopherperry commented Apr 27, 2021

Had to annotate usages with @InternalMavericksApi. When will there be an official API?

@gpeal
Copy link
Author

gpeal commented Apr 27, 2021

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