1

我一直在努力追随我能找到的唯一一个有支持的好例子,但就我而言,它不起作用。

我有一个与 Composable 中的 aViewModel对话,并根据 a 更改 a但它不会重新组合。@Modelloading: BoolMutableLiveData<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
        }
    }

}
4

1 回答 1

1

我正在做的是在我的 ViewModel 中有 Flows,并使用函数 collectAsState() whitin 组合。

于 2021-02-28T01:08:52.097 回答