how to have loading in Kotlin - 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
})
}
}

Related

Kotlin StateFlow multiple subscriptions after returning from another Fragment

I'm trying to implement StateFlow in my app with MVVM architecture between ViewModel and Fragment.
In ViewModel:
...
private val _eventDataState = MutableStateFlow<EventDataState>(EventDataState.Loading)
val eventDataState: StateFlow<EventDataState> = _eventDataState
...
In Fragment:
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.eventDataState.collect { eventDataState ->
when (eventDataState) {
is EventDataState.Loading -> {}
is EventDataState.Success -> onEventDataUpdated(data = eventDataState)
is EventDataState.Deleted -> onEventDataDeleted()
}
}
}
}
viewModel.getEventData()
}
...
All seems to work well:
2022-04-15 17:57:20.352 5251-5251/ ... E/EVENT: Data state: Success(...)
But when I switch to another Fragment through Activity's SupportFragmentManager and then hit Back button I get multiple responses from StateFlow:
2022-04-15 17:57:30.358 5251-5251/ ... E/EVENT: Data state: Success(...)
2022-04-15 17:57:30.362 5251-5251/ ... E/EVENT: Data state: Success(...)
So the more times I switch to another Fragment and back - the more copies of response I get from StateFlow (this is not initial StateFlow value).
My guess is that when another Fragment are called the first one destroys its view but subscription to Flow is still exists, and when returning back from another Fragment the first one calls its onViewCreated and so creating another copy of subscription to this Flow. Nevertheless I was unable to find any solution to my case on stackoverflow or any other resources.
What have I missed?
You should use viewLifecycleOwner.lifecycleScope.launch in fragments. viewLifecycleOwner.lifecycleScope and all its jobs will be cancelled when the view is destroyed.

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()

API data takes 2 button clicks in order to display data - Kotlin

I've tried searching stackoverflow, but couldn't find the answer to my issue. When the search button is clicked, I want the app to display the data from the API. The issue I'm having is that it is taking 2 clicks of the search button in order to display the data. The first click displays "null" and the second click displays all data correctly. What am I doing wrong? What do I need to change in order to process correctly on the first click? Thanks in advance!
Pairing Fragment
package com.example.winepairing.view.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.activityViewModels
import com.example.winepairing.databinding.FragmentPairingBinding
import com.example.winepairing.utils.hideKeyboard
import com.example.winepairing.viewmodel.PairingsViewModel
class PairingFragment : Fragment() {
private var _binding: FragmentPairingBinding? = null
private val binding get() = _binding!!
private val viewModel: PairingsViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentPairingBinding.inflate(inflater, container, false)
val view = binding.root
val toolbar = binding.toolbar
(activity as AppCompatActivity).setSupportActionBar(toolbar)
binding.searchBtn.setOnClickListener {
hideKeyboard()
if (binding.userItem.text.isNullOrEmpty()) {
Toast.makeText(this#PairingFragment.requireActivity(),
"Please enter a food, entree, or cuisine",
Toast.LENGTH_SHORT).show()
} else {
val foodItem = binding.userItem.text.toString()
getWinePairing(foodItem)
pairedWinesList()
pairingInfo()
}
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun pairedWinesList() {
val pairedWines = viewModel.apiResponse.value?.pairedWines
var content = ""
if (pairedWines != null) {
for (i in 0 until pairedWines.size) {
//Append all the values to a string
content += pairedWines.get(i)
content += "\n"
}
}
binding.pairingWines.setText(content)
}
private fun pairingInfo() {
val pairingInfo = viewModel.apiResponse.value?.pairingText.toString()
binding.pairingInfo.setText(pairingInfo)
}
private fun getWinePairing(foodItem: String) {
viewModel.getWinePairings(foodItem.lowercase())
}
}
So, sorry!!! Here is the viewmodel
package com.example.winepairing.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.winepairing.BuildConfig
import com.example.winepairing.model.data.Wine
import com.example.winepairing.model.network.WineApi
import kotlinx.coroutines.launch
const val CLIENT_ID = BuildConfig.SPOONACULAR_ACCESS_KEY
class PairingsViewModel: ViewModel() {
private val _apiResponse = MutableLiveData<Wine>()
val apiResponse: LiveData<Wine> = _apiResponse
fun getWinePairings(food: String) {
viewModelScope.launch {
_apiResponse.value = WineApi.retrofitService.getWinePairing(food, CLIENT_ID)
}
}
}
Although you didn't share your ViewModel code, I'm guessing that your ViewModel's getWinePairings() function retrieves data asynchronously from an API and then updates a LiveData called apiResponse with the return value. Since the API response takes some time before it returns, your apiResponse LiveData is going to still be empty by the time you call the Fragment's pairedWinesList() function from the click listener.
Hint, any time you use the .value of a LiveData outside of the ViewModel that manages it, you are probably doing something wrong. The point of LiveData is to react to it's data when it arrives, so you should be calling observe() on it instead of trying to read its .value synchronously.
More information in this question about asynchronous calls.
You haven't posted your actual code for fetching data from the API (probably in viewModel#getWinePairings), but at a guess it's going like this in your button click listener:
you call getWinePairing - this kicks off an async call that will eventually complete and set data on viewModel.apiResponse, sometime in the future. It's initial value is null
you call pairedWinesList which references the current value of apiResponse - this is gonna be null until an API call sets a value on it. Since you're basically fetching the most recent completed search result, if you change your search data then you'll end up displaying the results of the previous search, while the API call runs in the background and updates apiResponse later
you call pairingInfo() which is the same as above, you're looking at a stale value before the API call returns with the new results
The problem here is you're doing async calls that take a while to complete, but you're trying to display the results immediately by reading the current value of your apiResponse LiveData. You shouldn't be doing that, you should be using a more reactive design that observes the LiveData, and updates your UI when something happens (i.e. when you get new results):
// in onCreateView, set everything up
viewModel.apiResponse.observe(viewLifeCycleOwner) { response ->
// this is called when a new 'response' comes in, so you can
// react to that by updating your UI as appropriate
binding.pairingInfo.setText(response.pairingInfo.toString())
// this is a way you can combine all your wine strings FYI
val wines = response.pairedWines?.joinToString(separator="\n") ?: ""
binding.pairingWines.setText(wines)
}
binding.searchBtn.setOnClickListener {
...
} else {
val foodItem = binding.userItem.text.toString()
// kick off the API request - we don't display anything here, the observing
// function above handles that when we get the results back
getWinePairing(foodItem)
}
}
Hopefully that makes sense - the button click listener just starts the async fetch operation (which could be a network call, or a slow database call, or a fast in-memory fetch that wouldn't block the thread - the fragment doesn't need to know the details!) and the observe function handles displaying the new state in the UI, whenever it arrives.
The advantage is you're separating everything out - the viewmodel handles state, the UI just handles things like clicks (updating the viewmodel) and displaying the new state (reacting to changes in the viewmodel). That way you can also do things like have the VM save its own state, and when it initialises, the UI will just react to that change and display it automatically. It doesn't need to know what caused that change, y'know?

Android RecyclerView NotifyDataSetChanged with LiveData

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?

How to Block Fragment Re-Creation When BottomNavigationView's Tabs Selected?

I am trying to use a new Navigation structure on my sample project.
I used BottomNavigationView in activity.xml, and it launches with NavigationController.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launcher)
val navController = Navigation.findNavController(this, R.id.navHostFragment)
NavigationUI.setupWithNavController(bottomNavigation, navController)
}
That's great so far, but every time I click on the tabs, the relative fragments are recreated every time.
How can I prevent this behavior?
I don't want to create new fragments each time.
I just want to use the first created fragments.
Note: I didn't use setOnNavigationItemSelectedListener() or any other listeners. The navigation structure itself regenerates the fragments.
You can prevent creation of new fragment every time by saving the last created fragment instance.
You need to create fragment stack list : val mFragmentStacks: MutableList<Stack<Fragment>>
You need to save fragmnet instance according to tab position : mFragmentStacks[currentStackIndex].push(fragment)
Check first the stack has any entry then attach the last fragment otherwise create new fragment.
if (!mFragmentStacks[index].isEmpty()) {
val fragment = mFragmentStacks[currentStackIndex].peek()
} else {
val fragment = DemoFragment()
mFragmentStacks[currentStackIndex].push(fragment)
}
To avoid the recreation fragment, you can check if there is an instance of this one on the backstack.
You can use the tag of backtask to search after for especific fragment instances