Jetpack Composable doesn't react to changes

1

I've been trying to follow the only good example with support that I could find, but in my case, it doesn't work.

I have a ViewModel that talks to a @Model in Composable, and changes a loading: Bool according to a MutableLiveData<Boolean> but it doesn't recompose.

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 Answer

1

What I am doing, is to have Flows in my ViewModel, and use function collectAsState() whitin composables.

answered on Stack Overflow Feb 28, 2021 by Maximiliano S.

User contributions licensed under CC BY-SA 3.0