Skip to content

Instantly share code, notes, and snippets.

@cjbrooks12
Last active May 10, 2022 15:03
Show Gist options
  • Save cjbrooks12/606280822c383b26b3cff5c76ec3c6d6 to your computer and use it in GitHub Desktop.
Save cjbrooks12/606280822c383b26b3cff5c76ec3c6d6 to your computer and use it in GitHub Desktop.
Android KMM Strategies
public class ExampleViewModel : ViewModel() {
private val state = mutableStateFlowOf(ExampleFragmentState())
public fun observeStates(): StateFlow<ExampleFragmentState> = state.asStateFlow()
public fun button1Clicked() = viewModelScope.launch {
// ...
}
public fun button2Clicked() = viewModelScope.launch {
// ...
}
}
@AndroidEntryPoint
class ExampleFragment : ComposeFragment() {
private val viewModel: ExampleViewModel by viewModels() // shared ViewModel, injected by Hilt
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return ComposeView(requireContext()).apply {
setContent {
MaterialTheme {
val uiState by viewModel.observeStates().collectAsState() // data is emitted from the shared ViewModel with a StateFlow
ExampleContent(uiState)
}
}
}
}
@Composable
fun ExampleContent(
state: ExampleFragmentState
) {
Text("${state.count}")
Button(onClick = { viewModel.button1Clicked() }) {
Text("Button 1")
}
Button(onClick = { viewModel.button2Clicked() }) {
Text("Button 2")
}
}
}
@AndroidEntryPoint
class ExampleFragment : ComposeFragment() {
private val viewModel: ExampleViewModel by viewModels() // shared ViewModel, injected by Hilt
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return ExampleFragmentBinding
.inflate(inflater, container, false)
.also { binding = it }
.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// data is emitted from the shared ViewModel with a StateFlow
lifecycleScope.launchWhenResumed {
lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
viewModel.observeStates()
.onEach { state -> binding?.updateWithState(state) }
.launchIn(this)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private fun ExampleFragmentBinding.updateWithState(state: ExampleFragmentState) {
textView.text = "${state.count}"
btn1.setOnClickListener { viewModel.button1Clicked() }
btn2.setOnClickListener { viewModel.button2Clicked() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment