【问题标题】:Jetpack Composable doesn't react to changesJetpack Composable 不会对更改做出反应
【发布时间】:2020-02-26 12:29:42
【问题描述】:

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

我有一个 ViewModel 与 Composable 中的 @Model 对话,并根据 MutableLiveData<Boolean> 更改 loading: Bool 但它不会重新组合。

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
        }
    }

}

【问题讨论】:

    标签: android android-fragments android-livedata android-viewmodel android-jetpack-compose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多