Android RecyclerView NotifyDataSetChanged with LiveData - kotlin

When instantiating the ListAdapter for my RecyclerView, I call:
viewModel.currentList.observe(viewLifecycleOwner){
adapter.submitList(it)
}
which is what I've seen done in the Android Sunflower project as the proper way to submit LiveData to a RecyclerView. This works fine, and when I add items to my database they are updated in the RecyclerView. However, if I write
viewModel.currentList.observe(viewLifecycleOwner){
adapter.submitList(it)
adapter.notifyDataSetChanged()
}
Then my adapters data observer always lags behind. I call
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver(){
override fun onChanged() {
super.onChanged()
if (adapter.currentList.isEmpty()) {
empty_dataset_text_view.visibility = View.VISIBLE
} else {
empty_dataset_text_view.visibility = View.GONE
}
}
})
And empty_dataset_text_view appears one change after the list size reached zero, and likewise it disappears one change after the list size is non-zero.
Clearly, the observer is running the code before it has submitted it which in this case is LiveData queried from Room. I'd simply like to know what the workaround is for this: is there a way to "await" a return from my LiveData?

Related

Lazycolumn with lazyrow that are loaded with api call

i'am new to jetpack compose and i would like to achieve a view but i'am really struggling with it. it a catalogue movie where you can chose film in different categories, so you get the all the categories listed in column and for each category you get multiples films in the row.
Here is what i want to do : i have a viewmodele to make call to my api. So i make a first call giving me the list of categories. then for each category have to make an other call of my view modele to get films of this category. Here is how i started :
class CatalogViewModel() : ViewModel() {
var loadCategories by mutableStateOf(false)
var categories: ArrayList<Category> = arrayListOf()
init {
fetchCategories()
}
fun fetchCategories() {
this.viewModelScope.launch {
Api.Call(
completionHandler = object : completionHandler<ArrayList<Category>, Error> {
override fun succeed(result: ArrayList<Category>?) {
loadCategories = true
if (result != null) {
categories = result
loadCategories = true
}
}
override fun failed(error: PKError?) {
println("failed")
loadCatalog = false
}
})
}
}
completionHandler is just and interface that we use to make our api call :
interface completionHandler<in T, in U> {
fun succeed(result: T?)
fun failed(error: U?)}
So first of all i don't really know how states work in jetpack compose so i'am not sure if i'am doing it good or not but it's work, now in my composable i just have to check
if (CatalogViewModel.loadCategories)
Then i can display my list of categories. But here is where i don't know how to do further : now for each category i have to make an other call to get the film that i need to display is the row, but i can't use the same technique because i'am not sur how much call i'll need to do, so i can't have a mutable state of boolean to observe in order to compose my row. So how can i do a call for each row and compose when the call is done ? also this has to be asynchrone because i can't wait all row to be loaded to display them.
And in a second time, i'll maybe get a lot of categories so i would like to only load those displayed on the screen.
I feel like i'am doing something wrong or maybe i didn't really get how to work with jetpack compose. So i would really like some help, thanks

Collecting Flow<List> and displaying it in Compose (Kotlin)

Hello guys I have list of movies that I call from MovieApi.
In movieRepo I did this:
override suspend fun getPopularMovies() : Flow<List<Movie>>{
val popularMovies : Flow<List<Movie>> = flow{
while(true){
val lastMovie = movieApi.getPopularMovies()
Log.i("EMIT", "${emit(lastMovie)}")
kotlinx.coroutines.delay(5000)
}
}
return popularMovies
}
In MovieViewModel:
init{
viewModelScope.launch {
repository.getPopularMovies().collect(){
Log.i("COLLECTED", "$it")
}
}
}
private suspend fun getPopularMovies() {
return repository.getPopularMovies().collect()
}
I know that collect gets all Movies I want, but I need to display it in my HomeScreen with viewModel when I call getPopularMovies.
I'm reading Flow docs but cant understan how this part works(news part is from Flow documentation):
newsRepository.favoriteLatestNews.collect { favoriteNews ->
// Update View with the latest favorite news
}
I have the same question too actually. Curious to see if you had found out anything.
I could be mistaken in this but I would like to gain a better understanding in this so I would appreciate for other to chime in as well.
Assuming you're using targeting a recyclerview.
For non-Viewmodel collection approach, the collection has to be done in the UI layer.
In collect block, you will need to pass movie list to adapter's submitList.
But if you still want to do collection in ViewModel, you will need to create a UIState as a StateFlow. Collect the movie list into a UI state.
In UI layer, collect the UI state and access the movie list from it

Why doesn't App crash when I use collect a flow from the UI directly from launch in Jetpack Compose?

I have read the article. I know the following content just like Image B.
Warning: Never collect a flow from the UI directly from launch or the launchIn extension function if the UI needs to be updated. These functions process events even when the view is not visible. This behavior can lead to app crashes. To avoid that, use the repeatOnLifecycle API as shown above.
But the Code A can work well without wrapped with repeatOnLifecycle, why?
Code A
#Composable
fun Greeting(handleMeter: HandleMeter,lifecycleScope: LifecycleCoroutineScope) {
Column(
modifier = Modifier.fillMaxSize()
) {
var my by remember { mutableStateOf(5)}
Text(text = "OK ${my}")
var dataInfo = remember { handleMeter.uiState }
lifecycleScope.launch {
dataInfo.collect { my=dataInfo.value }
}
}
class HandleMeter: ViewModel() {
val uiState = MutableStateFlow<Int>(0)
...
}
Image B
Code A will not work in real life. If you need to run some non-UI code in a composable function, use callbacks (like onClick) or LaunchedEffect (or other side effects).
LaunchedEffect {
dataInfo.collect {my=dataInfo.value}
}
Side effects are bound to composables, there is no need to specify the owner of their lifecycle directly.
Also, you can easily convert any flow to state:
val my = handleMeter.uiState.collectAsState()

Handle To Remove/Add Live Data Observer to Observe On Button Click

I want to to observe a row in room database. it change after some period. but when we stop button click it need to be stop observing form database and when click start button it start observing again.
My current code is
To create Observer
private lateinit var recordObserver: Observer<Ride>
recordObserver= Observer<Ride> { rides ->
if (rides != null)
updateData(rides)
else
setDataToZero()
}
when(isState){
Constants.isrunning->{//need to start observer}
Constants.Stop->{//need to stop observer}
}
In order to start/stop observing LiveData you should use observe() / removeObserver() methods. As simple as that. If you have access to LifecycleOwner (Fragment, Activity) use fun observe(), if not - use fun observeForever().
Your code will look like this:
val liveData = database.observeRides() // get your live data
when(isState){
Constants.isrunning -> {
liveData.observe(this, recordObserver)
}
Constants.Stop -> {
liveData.removeObserver(recordObserver)
}
}

how to have loading in Kotlin

my MainActivity contains a ViewPager that loads 4 fragments, each fragment should load lots of data from the server.
so when my app wants to be run for the first time, it almost takes more than 3 seconds and the other times(for example, if you exit the app but not clean it from your 'recently app' window and reopen it) it takes almost 1 second.
while it is loading, it shows a white screen.
is there any way instead of showing a white screen till data become ready, I show my own image?
something like the splash page?
If you do long-running actions on the main thread, you risk getting an ANR crash.
Your layout for each fragment should have a loading view that is initially visible, and your data view. Something like this:
(not code)
FrameLayout
loading_view (can show a progress spinner or something, size is match parent)
content_view (probably a RecyclerView, initial visibility=GONE, size is match parent)
/FrameLayout
You need to do your long running action on a background thread or coroutine, and then swap the visibility of these two views when the data is ready to show in the UI.
You should not be directly handling the loading of data in your Fragment code, as Fragment is a UI controller. The Android Jetpack libraries provide the ViewModel class for this purpose. You would set up your ViewModel something like this. In this example, MyData could be anything. In your case it's likely a List or Set of something.
class MyBigDataViewModel(application: Application): AndroidViewModel(application) {
private val _myBigLiveData = MutableLiveData<MyData>()
val myBigLiveData: LiveData<MyData>() = _myBigLiveData
init {
loadMyBigData()
}
private fun loadMyBigData() {
viewModelScope.launch { // start a coroutine in the main UI thread
val myData: MyData = withContext(Dispatchers.Default) {
// code in this block is done on background coroutine
// Calculate MyData here and return it from lambda
// If you have a big for-loop, you might want to call yield()
// inside the loop to allow this job to be cancelled early if
// the Activity is closed before loading was finished.
//...
return#withContext calculatedData
}
// LiveData can only be accessed from the main UI thread so
// we do it outside the withContext block
_myBigLiveData.value = myData
}
}
}
Then in your fragment, you observe the live data to update the UI when it is ready. The below uses the fragment-ktx library, which you need to add to your project. You definitely should read the documentation on ViewModel.
class MyFragment: Fragment() {
// ViewModels should not be instantiated directly, or they won't be scoped to the
// UI life cycle correctly. The activityViewModels delegate handles instantiation for us.
private val model: MyBigDataViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.myBigLiveData.observe(this, Observer<MyData> { myData ->
loading_view.visibility = View.GONE
content_view.visibility = View.VISIBLE
// use myData to update the view content
})
}
}