I have a very strange problem with my LazyColumn. I am updating the menuList State in the ViewModel, the view recomposes but the list doesn't get redrawn.
When I use the debugger, it gets to LazyColumn and then stops, which means the children aren’t redrawn with the new data. Any ideas why? Thanks!
MyView:
val menuList = viewModel.menuData.observeAsState()
LazyColumn() { // <- Debugger stops here
items(menuList.value.sections.size) { i->
MenuItem(menuList.value[i])
}
}
MyViewModel:
private var menu: MenuUiState? = null
val menuData: MutableLiveData<MenuUiState> by lazy {
MutableLiveData<MenuUiState>()
}
// ...
menu?.sections?.forEach {
//update menu properties here
}
menuData.value = menu?.copy()
You are observing the MenuUiState object, but you are not actually observing changes made to the items of the sections list.
You should either make sections a MutableStateList inside MenuUiState, or have the ViewModel store it directly:
val sections = mutableStateListOf<Section>() // store it either inside the ViewModel or inside MenuUiState
Then just observe it in the composable normally:
LazyColumn() { // <- Debugger stops here
items(viewModel.sections) { section ->
MenuItem(section)
}
}
Related
I have a Compose screen, with two separate components:
horizontal scroll of items
vertical scroll of card items, which need to be paginated
I also have a ViewModel attached to that screen which provides the state:
val viewState: StateFlow<MyScreenState> = _viewState
...
data class MyScreenState(
val horizontalObjects: List<MyObject>,
val verticalCardsPaged: Flow<PagingData<MyCard>>
)
The cards are paged, the horizontal list doesn't have to be. In the Compose screen, I receive and use the state like so:
val state = viewModel.viewState.collectAsState().value
MyScreen(state)
...
#Composable
fun MyScreen(state: MyScreenState) {
val cards: LazyPagingItems<MyCard> = state.verticalCardsPaged.collectAsLazyPagingItems()
LazyRow {
items(state.horizontalObjects) {
...
}
}
LazyColumn {
items(cards) {
...
}
}
}
So I have a Flow inside Flow, effectively. It all seems to be working ok, but I'm not sure if I should be combining them instead of nesting? What would be the preferred approach here?
I'm trying to implement some kind of LaunchedEffectOnce as I want to track a ContentViewed event. So my requirement is that every time the user sees the content provided by the composable, an event should get tracked.
Here is some example code of my problem:
#Composable
fun MyScreen(viewModel: MyViewModel = get()){
val items by viewModel.itemsToDisplay.collectAsState(initial = emptyList())
ItemList(items)
// when the UI is displayed, the VM should track an event (only once)
LaunchedEffectOnce { viewModel.trackContentViewed() }
}
#Composable
private fun LaunchedEffectOnce(doOnce: () -> Unit) {
var wasExecuted by rememberSaveable { mutableStateOf(false) }
if (!wasExecuted) {
LaunchedEffect(key1 = rememberUpdatedState(newValue = executed)) {
doOnce()
wasExecuted = true
}
}
}
This code is doing do the following:
Tracks event when MyScreen is composed
Does NOT track when the user enters a list item screen and navigates back to MyScreen
Does NOT track the event on recomposition (like orientation change)
But what I wan't to achieve is the following:
Tracks event when MyScreen is composed
Tracks when the user enters a list item screen and navigates back to MyScreen
Does NOT track the event on recomposition (like orientation change)
My ViewModel looks like that:
class MyViewModel() : ViewModel() {
val itemsToDisplay: Flow<List<Item>> = GetItemsUseCase()
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), replay = 1)
val contentTracking: Flow<Tracking?> = GetTrackingUseCase()
.distinctUntilChanged { old, new -> old === new }
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), replay = 1)
fun trackContentViewed(){
// track last element in contentTracking
}
}
I really hope someone can help me and can explain what I'm doing wrong here. Thanks in advance!
Assuming the following are true
your view model is scoped to the Fragment in which MyScreen enters composition
your composables leave the composition when you navigate to an item screen and re-enter composition when you navigate back
then you can simply track inside the view model itself whether specific content was already viewed in this view model's scope. Then when you navigate to any of the items screens you reset that "tracking state".
If you need to track only a single element of content then just a Boolean variable would be enough, but in case you need to track more than one element, you can use either a HashSet or a mutableSetOf (which returns a LinkedHashSet instead). Then when you navigate to any of the item screen you reset that variable or clear the Set.
Your VM code would then change to
class MyViewModel() : ViewModel() {
// ... you existing code remains unchanged
private var viewedContent = mutableSetOf<Any>()
fun trackContentViewed(key: Any){
if (viewedContent.add(key)) {
// track last element in contentTracking
Log.d("Example", "Key $key tracked for 'first time'")
} else {
// content already viewed for this key
Log.d("Example", "Key $key already tracked before")
}
}
fun clearTrackedContent() {
viewedContent.clear()
}
}
and the MyScreen composable would change to
#Composable
fun MyScreen(viewModel: MyViewModel = get()){
// ... you existing code remains unchanged
// Every time this UI enters the composition (but not on recomposition)
// the VM will be notified
LaunchedEffect(Unit) {
viewModel.trackContentViewed(key = "MyScreen") // or some other key
}
}
Where you start the navigation to an item screen (probably in some onClick handler on items) you would call viewmodel.clearTrackedContent().
Since (1) is true when ViewModels are requested inside a Fragment/Activity and if (2) is also true in your case, then the VM instance will survive configuration changes (orientation change, language change...) and the Set will take care of tracking.
If (2) is not true in your case, then you have two options:
if at least recomposition happens when navigating back, replace LaunchedEffect with SideEffect { viewModel.trackContentViewed(key = "MyScreen") }
if your composables are not even recomposed then you will have to call viewModel.trackContentViewed also when navigating back.
so I wasted a good couple of days on this, and my deadline's tomorrow
basically, I have a mutableLiveData var which is a companion object,
and when the data is updated it calls the observe function inside the grid.
The observe function gets called fine, it does the print statements which you can see,
but it completely skips everything in the compose "items()" method.
Can someone please help me? I could not find anything useful online...
#ExperimentalFoundationApi
#Composable
fun ItemsGrid() {
LazyVerticalGrid(
cells = GridCells.Fixed(3),
contentPadding = PaddingValues(8.dp)
) {
mProductsByCategoryID.observe(viewLifecycleOwner,
{ products ->
println("DATA CHANGGED ${products[0].name}")
println(mProductsByCategoryID.value?.get(0)?.name)
items(products) {
println("INSIDE ITEMS for products ${it.name}") // never gets inside of here except for the first time the view loads
DemoCards(demo = it)
}
}
)
}
}
In Compose you shouldn't observe LiveData directly inside a #Composable, but observe it as State. Instead of callbacks to update UI, now we have Recomposition (#Composable function getting called automatically over and over again every time an observed value in the #Composable function changes).
More info here
Your code should look more like:
#Composable
fun ItemsGrid() {
val productsByCategory = mProductsByCategoryID.observeAsState()
LazyVerticalGrid(
cells = GridCells.Fixed(3),
contentPadding = PaddingValues(8.dp)
) {
//here goes code that does what your callback was doing before.
//when val productsByCategory.value changes, ItemsGrid()
//gets recomposed (called again) and this code will execute
}
}
I'm using androidx.paging:paging-compose (v1.0.0-alpha-14), together with Jetpack Compose (v1.0.3), I have a custom PagingSource which is responsible for pulling items from backend.
I also use compose navigation component.
The problem is I don't know how to save a state of Pager flow between navigating to different screen via NavHostController and going back (scroll state and cached items).
I was trying to save state via rememberSaveable but it cannot be done as it is not something which can be putted to Bundle.
Is there a quick/easy step to do it?
My sample code:
#Composable
fun SampleScreen(
composeNavController: NavHostController? = null,
myPagingSource: PagingSource<Int, MyItem>,
) {
val pager = remember { // rememberSaveable doesn't seems to work here
Pager(
config = PagingConfig(
pageSize = 25,
),
initialKey = 0,
pagingSourceFactory = myPagingSource
)
}
val lazyPagingItems = pager.flow.collectAsLazyPagingItems()
LazyColumn() {
itemsIndexed(items = lazyPagingItems) { index, item ->
MyRowItem(item) {
composeNavController?.navigate(...)
}
}
}
}
I found a solution!
#Composable
fun Sample(data: Flow<PagingData<Something>>):
val listState: LazyListState = rememberLazyListState()
val items: LazyPagingItems<Something> = data.collectAsLazyPagingItems()
when {
items.itemCount == 0 -> LoadingScreen()
else -> {
LazyColumn(state = listState, ...) {
...
}
}
}
...
I just found out what the issue is when using Paging.
The reason the list scroll position is not remembered with Paging when navigating boils down to what happens below the hood.
It looks like this:
Composable with LazyColumn is created.
We asynchronously request our list data from the pager. Current pager list item count = 0.
The UI draws a lazyColumn with 0 items.
The pager responds with data, e.g. 10 items, and the UI is recomposed to show them.
User scrolls e.g. all the way down and clicks the bottom item, which navigates them elsewhere.
User navigates back using e.g. the back button.
Uh oh. Due to navigation, our composable with LazyColumn is recomposed. We start again with asynchronously requesting pager data. Note: pager item count = 0 again!
rememberLazyListState is evaluated, and it tells the UI that the user scrolled down all the way, so it now should go back to the same offset, e.g. to the fifth item.
This is the point where the UI screams in wild confusion, as the pager has 0 items, so the lazyColumn has 0 items.
The UI cannot handle the scroll offset to the fifth item. The scroll position is set to just show from item 0, as there are only 0 items.
What happens next:
The pager responds that there are e.g. 10 items again, causing another recomposition.
After recomposition, we see our list again, with scroll position starting on item 0.
To confirm this is the case with your code, add a simple log statement just above the LazyColumn call:
Log.w("TEST", "List state recompose. " +
"first_visible=${listState.firstVisibleItemIndex}, " +
"offset=${listState.firstVisibleItemScrollOffset}, " +
"amount items=${items.itemCount}")
You should see, upon navigating back, a log line stating the exact same first_visible and offset, but with amount items=0.
The line directly after that will show that first_visible and offset are reset to 0.
My solution works, because it skips using the listState until the pager has loaded the data.
Once loaded, the correct values still reside in the listState, and the scroll position is correctly restored.
Source: https://issuetracker.google.com/issues/177245496
Save the list state in your viewmodel and reload it when you navigate back to the screen containing the list. You can use LazyListState in your viewmodel to save the state and pass that into your composable as a parameter. Something like this:
class MyViewModel: ViewModel() {
var listState = LazyListState()
}
#Composable
fun MessageListHandler() {
MessageList(
messages: viewmodel.messages,
listState = viewmode.listState
)
}
#Composable
fun MessageList(
messages: List<Message>,
listState: LazyListState) {
LazyColumn(state = listState) {
}
}
If you don't like the limitations that Navigation Compose puts on you, you can try using Jetmagic. It allows you to pass any object between screens and even manages your viewmodels in a way that makes them easier to access from any composable:
https://github.com/JohannBlake/Jetmagic
The issue is that when you navigate forward and back your composable will recompose and collectAsLazyPagingItems() will be called again, triggering a new network request.
If you want to avoid this issue, you should call pager.flow.cacheIn(viewModelScope) on your ViewModel with activity scope (the ViewModel instance is kept across fragments) before calling collectAsLazyPagingItems().
LazyPagingItems is not intended as a persistent data store; it is just a simple wrapper for the UI layer. Pager data should be cached in the ViewModel.
please try using '.cachedIn(viewModelScope) '
simple example:
#Composable
fun Simple() {
val simpleViewModel:SimpleViewModel = viewModel()
val list = simpleViewModel.simpleList.collectAsLazyPagingItems()
when (list.loadState.refresh) {
is LoadState.Error -> {
//..
}
is LoadState.Loading -> {
BoxProgress()
}
is LoadState.NotLoading -> {
when (list.itemCount) {
0 -> {
//..
}
else -> {
LazyColumn(){
items(list) { b ->
//..
}
}
}
}
}
}
//..
}
class SimpleViewModel : ViewModel() {
val simpleList = Pager(
PagingConfig(PAGE_SIZE),
pagingSourceFactory = { SimpleSource() }).flow.cachedIn(viewModelScope)
}
I've got a composable on a Screen which shows a list of Track items (favourites) :
var favourites: MutableList<Track> by mutableStateOf(mutableListOf())
#ExperimentalFoundationApi
#Composable
private fun ResultList(model: FreezerModel) {
with(model) {
if (favourites.isEmpty()) NoDataMessage("No favourites yet")
else {
LazyColumn(state = rememberLazyListState()) {
items(favourites) {
TrackCard(it, model)
}
}
}
}
}
On click events, I am updating my favourites list (add/remove item). How can I make my composable reflect these changes immediately (like to re-draw itself or something similar)? So far, it only works when I first switch to another screen.
Thanks for your inputs!
You need to use a MutableStateList<T> so that Compose can automatically recompose when the state changes.
From official doc:
Caution: Using mutable objects such as ArrayList<T> or mutableListOf() as state in Compose will cause your users to see incorrect or stale data in your app.
In your code use
val favourites = remember { mutableStateListOf<Track>()}
instead of
var favourites: MutableList<Track> by mutableStateOf(mutableListOf())
Just removing state = rememberLazyListState() from the lazyColumnFor params list should work in your case.
According to the doc if we use rememberLazyListState() then :-
Changes to the provided initial values will not result in the state being recreated or changed in any way if it has already been created.
After doing so , normally updating the list should work fine. Also its a good practice to expose an immutable list ( list ) instead of a mutableList to the composable.
For example use:-
var favourites by mutableStateOf(listOf<FavoriteItem>())
then add/remove/update the list by using :-
favourites = favourites + newList // add
favourites = favourites.toMutableList().also { it.remove(item) } // remove