-
-
Save gpeal/5bed618a843d4d71bb1518fa8317c5df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun MyComposable() { | |
val viewModel: MyViewModel = mavericksViewModel() | |
val state = viewModel.collectAsState() | |
AnotherComposable( | |
state.value, | |
onClick = viewModel.onClick() | |
) | |
} |
@tinder-christopherperry mavericks-compose
is officially out
https://airbnb.io/mavericks/#/jetpack-compose
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had to annotate usages with
@InternalMavericksApi
. When will there be an official API?