https://kotlinlang.org logo
#coroutines
Title
# coroutines
f

Florian

10/28/2020, 9:09 PM
Has anyone here used the new Jetpack DataStore yet? I want to restore the checked state of a checkbox options menu item when a fragment is created. 1. I use
first()
because I only need to set the value from DataStore once, afterwards just clicking the checkbox will check/uncheck it. Does this make sense? Are there any situations where it will break? 2. Is the asynchronicity a problem? As far as I understand, you can't read from DataSore synchronously so this is the only option I can see.
Copy code
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    
    [...]
    
    viewLifecycleOwner.lifecycleScope.launch {
        menu.findItem(R.id.action_hide_completed_tasks).isChecked =
            viewModel.preferencesFlow.first().hideCompleted
    }
}
l

louiscad

10/29/2020, 6:53 AM
You can also update the menu when the flow gives a new value.
f

Florian

10/29/2020, 9:52 AM
you mean removing
first()
?
l

louiscad

10/29/2020, 9:58 AM
Using collect, collectLatest or onEach + launchIn and update the menu with any changes
f

Florian

10/29/2020, 10:19 AM
ok, thanks
5 Views