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

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

Related

Thread-safe access to the same variable from different flows (Kotlin)

Is this code thread safe? Do I need a synchronized block or something like that? source1 and source2 endless Kotlin Flow
viewModelScope.launch {
var listAll = mutableListOf<String>()
var list1 = mutableListOf<String>()
var list2 = mutableListOf<String>()
launch {
source1.getNames().collect { list ->
list1 = list
listAll = mutableListOf()
listAll.addAll(list1)
listAll.addAll(list2)
//then consume listAll as StateFlow or return another flow with emit(listAll)
}
}
launch {
source2.getNames().collect { list ->
list2 = list
listAll = mutableListOf()
listAll.addAll(list2)
listAll.addAll(list1)
//then consume listAll as StateFlow or return another flow with emit(listAll)
}
}
}
This code is not thread safe.
However, it is called from viewModelScope.launch which runs on Dispatchers.Main by default. So your inner launch blocks will be called sequentially. This means that after all you will get the result which is produced by second launch block.
To achieve asynchronous behavior, you want to use viewModelScope.launch(Dispatchers.Default).
Your code will probably fire concurrent modification exception in that case.
To synchronize it, you may want to use Java's Collections.synchronizedList which blocks the list while one thread is performing operations with it, so the other thread are not able to perform modifications.
Or perform synchronizing manually using Mutex.
val mutex = Mutex()
viewModelScope.launch(Dispatchers.Default) {
launch {
mutex.withLock {
... // Your code
}
}
launch {
mutex.withLock {
... // Your code
}
}
}
Read official Kotlin guide to shared mutable state
After all, I am struggling to imagine real life example in which you will actually use that code. You probably don't need asynchronous behavior, you will be fine without using two launch blocks. Or you should rethink your design to avoid need of manual synchronization of two coroutines.

stringResource() causing recompose of composition

I am beginner at jetpack compose. I was debugging recomposition but suddenly I saw a unusual recomposition in Header compose function when app start.
I find out the reason or culprit for the recomposition that I used in Header compose function to get string text by stringResource().. If I use context.getString() or hardcode string value instead of stringResource() then I got no recomposition.
This code when showing the recomposition
#Composable
fun MainScreen() {
Header()
}
#Composable
fun Header() {
Text(
text = stringResource(id = R.string.app_name)
)
}
But If I use these codes No more recomposition. But why?
#Composable
fun MainScreen() {
Header()
}
#Composable
fun Header() {
val context = LocalContext.current
Text(
text = context.getString(R.string.app_name)
)
}
So what can I do for get rid of recomposition when using stringResource() into compose functions
if you have the value saved in the res/values/strings.xml file then using compose the only thing you will need to do is calling the stringResource(R.string.app_name). Jetpack Compose handles getting the resource on its own. you wont even need to get it from your Context.
see here for docs on resource.
that should not cause recomposing every time but if it does it is always a good practice to save your values inside of a remember so that it knows not to recompose every time. the problem might be from a different part of your code.
First of all, this behavior shouldn't be happening, I recommend creating a clean project and trying again.
But... to avoid recomposing inside Composable, the Effect API would be useful:
val context = LocalContext.current
var appName = ""
LaunchedEffect(Unit) {
appName = context.getString(R.string.app_name)
}
Text(
text = appName
)
The codes inside the LaunchedEffect block are only executed once, even if the recomposition happens.
Documentaion of api Side Effects

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

How to i chain two parts of an animation together in jetpack compose so the the offset increases then decreases?

Ive recently got into doing animations using jet pack compose and am wondering how you can make it so that when you increase a value in an offset, once the animation reaches that value it then changes the value to another value. So like update transition but instead of at the same time, one after the other.
Actually #RaBaKa's answer is partially correct, but it's missing information about how the animation should be run.
It should be done as a side effect. For example, you can use LaunchedEffect: it is already running in a coroutine scope. It is perfectly normal to run one animation after another - as soon as the first suspend function finishes, the second will be started:
val value = remember { Animatable(0f) }
LaunchedEffect(Unit) {
value.animateTo(
20f,
animationSpec = tween(2000),
)
value.animateTo(
10f,
animationSpec = tween(2000),
)
}
Text(value.value.toString())
If you want to do this in response to some action, such as pressing a button, you need to run the coroutine yourself. The main thing is to run the animations in the same coroutine so that they are chained.
val value = remember { Animatable(0f) }
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
value.animateTo(
20f,
animationSpec = tween(2000),
)
value.animateTo(
10f,
animationSpec = tween(2000),
)
}
}) {
}
Text(value.value.toString())
The correct answer is to use Kotlin coroutines. I managed to get it working fine. You have to use coroutines in order to launch the animations in the correct sequence like this:
animationRoutine.launch {
coroutineScope {
launch {
animate(
startingValue,
targetValue,
animationSpec = whatYouWant,
block = { value, _ -> whateverYouNeed = value }
)
}
launch {
animate(
initialValue,
targetValue,
animationSpec = whatYouWant,
block = { value, _ -> whateverYouNeed = value }
)
}
}
Each of launch scope launches everything in a non blocking way if you tell it to allowing you to run multiple animations at once at a lower level and to sequence the animations you add another coroutine for the next part of the animation.
Maybe you can use Animatable
val value = remember { Animatable(0f) } //Initial Value
Then in compose you can just use
value.animateTo(20f)
then
value.animateTo(10f)
For more information visit the official documentation

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