我一直在努力追随我能找到的唯一一个有支持的好例子,但就我而言,它不起作用。
我有一个与 Composable 中的 aViewModel
对话,并根据 a 更改 a但它不会重新组合。@Model
loading: Bool
MutableLiveData<Boolean>
class LoaderViewModel : ViewModel() {
val loadingLiveData = MutableLiveData<Boolean>(false)
fun fetch() {
viewModelScope.launch {
val flow = flowOf("result")
.onStart {
loadingLiveData.value = true
delay(2000)
}
.onCompletion {
loadingLiveData.value = false
}
.collect {
// Do something with the result
}
}
}
}
class LoaderFragment : Fragment() {
private val viewModel: LoaderViewModel by viewModel()
@Model
class ActivityLoadingState(var loading: Boolean = false)
private val activityLoadingState = ActivityLoadingState()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return FrameLayout(context ?: return null).apply {
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
setContent {
Loader()
}
}
}
@Composable
fun Loader() = MaterialTheme {
val loadingModel = activityLoadingState
Container {
Center {
if (loadingModel.loading) {
CircularProgressIndicator(
color = Color(0xFFFF0000)
)
} else {
Container { }
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
subscribeUI()
viewModel.fetch()
}
private fun subscribeUI() {
viewModel.loadingLiveData.observe(viewLifecycleOwner) {
activityLoadingState.loading = it
}
}
}