Questions tagged [kotlin-stateflow]
In Kotlin coroutines, a StateFlow is a mutable value whose changes can be observed as a flow. Use this tag for questions about publishing, transforming and consuming state flows.
kotlin-stateflow
265
questions
37
votes
1
answer
15k
views
MutableStateflow Value Vs Update vs Emit
Let say I have a MutableStateFlow variable. What is the main differences and usage of the three cases
mutable.value = 1
mutable.emit(2)
mutable.update {3}
33
votes
4
answers
31k
views
LiveData Vs StateFlow: Should we switch from Live data to State Flow?
I have come across articles that recommend switching to StateFlow.
Like the one here.
Also in the new Android studio, StateFlow support is automatically included in the functionality of data binding, ...
25
votes
4
answers
14k
views
Kotlin combine more than 2 flows
I'm looking to combine 4 StateFlow values and make 1 StateFlow from these. I know already of the combine function like this:
val buttonEnabled = cameraPermission.combine(micPermission) {
//some ...
25
votes
2
answers
17k
views
mutableState VS mutableStateFlow?
I'm confused, can someone explain to me, what's the main difference between those two? I'm having hard times understanding. mutableState was introduced with Jetpack Compose, and now my question is, ...
22
votes
4
answers
14k
views
Collect from several stateflows
I have 2 stateFlow's in my viewModel. To collect them in fragment I have to launch coroutines 2 times as below:
lifecycleScope.launchWhenStarted {
stocksVM.quotes.collect {
if (...
19
votes
2
answers
15k
views
Use of SharedFlow in Android kotlin
Hey I am learning flow in kotlin. I am learning about MutableStateFlow and MutableSharedFlow. I tried to learn MutableStateFlow in real world example. But I am unable to get the MutableSharedFlow ...
19
votes
2
answers
12k
views
Using map on Kotlin's Stateflow
With LiveData inside a Viewmodel we use switchMap or Transformations.map like this
val recipesList = cuisineType.switchMap { repository.getDisplayRecipes(it.cuisineType).asLiveData() }
What would be ...
19
votes
1
answer
2k
views
Android MVI using StateFlow and paging 3
I am trying to implement android MVI architecture using state flow and paging 3 but I got confused when I had a view state which contains paging data.
The problem is that I expose the view state from ...
17
votes
1
answer
5k
views
What are the differences between StateFlow and LiveData?
as I mentioned in the title, I'm curious about the general differences between the two. Can you help with this? I couldn't find the specific differences as there are complex examples on the internet.
...
13
votes
2
answers
9k
views
Android - How to read a value from a kotlin flow?
I have a flow of Episode from a room database.
I can observe as livedata this flow with no problem.
But I also would like to read the last value from this flow when the user clicks on a button. I ...
12
votes
2
answers
7k
views
StateFlow don't emit when the new value same last value
I have a login form. I use StateFlow to send LoginResult (after call API) from ViewModel to Activity. In the Activity, I will show an error dialog if login failed.
It works well for the first time but ...
11
votes
1
answer
3k
views
Expose value from SharedPreferences as Flow
I'm trying to get a display scaling feature to work with JetPack Compose. I have a ViewModel that exposes a shared preferences value as a flow, but it's definitely incorrect, as you can see below:
@...
10
votes
5
answers
7k
views
StateFlow last value is collected again in ui
So lately I've been working with StateFlow, SharedFlow, and Channels API's but I'm struggling with one common use case while trying to migrate my code from LiveData to StateFlow in the presentation ...
10
votes
3
answers
8k
views
Populate and emit StateFlow List
I want to use StateFlow. But for now, I don't find any lecture which could help me.
I'm facing an issue :
To start, I have a singleton which hold a list of String, I want something "easy" to ...
7
votes
1
answer
6k
views
Is collectAsStateWithLifecycle only applicable to cold flow, and not helpful for hot flow (e.g. stateFlow)?
Lately, we have a new API since android lifecycle library version 2.6.0-alpha01, i.e.
collectAsStateWithLifecycle(...)
It is advocated by Google Developer in this article
If you’re building an ...
7
votes
2
answers
8k
views
Combine two kotlin flows into a single flow that emits the latest value from the two original flows?
If we have two flows defined like this:
val someflow = flow {
emit("something")
}
and another flow defined like:
val stateFlow = MutableStateFlow("some value")
Is it possible ...
7
votes
2
answers
4k
views
Flow doesn't update Composable
I faced the following problem:
There's the registration screen, which has several input fields on it. When a user enters something, the value is passed to ViewModel, set to screen state and passed ...
7
votes
2
answers
3k
views
Android LiveData/StateFlow List Item Property Update Issue
So I'm updating my RecylerView with StateFlow<List> like following:
My data class:
data class Student(val name: String, var isSelected: Boolean)
My ViewModel logic:
fun ...
7
votes
1
answer
2k
views
Stateflow value not getting being observed in data binding
I have a stateflow that is giving me the value of a mutable state flow from ViewModel, what I am trying to do is, I want to show hide a webview based on a button click. When the value is true I want ...
7
votes
1
answer
4k
views
How to use DataStore with StateFlow and Jetpack Compose?
I try to give the user the choice whether to use the UI Mode 'light', 'dark' or the 'system' settings. I would like to save the selection as DataStore.
The drop down menu for the user selection is not ...
7
votes
2
answers
5k
views
Unit testing viewModel that uses StateFlow and Coroutines
Kotlin 1.4.21
I have a very simple ViewModel that uses coroutine and stateFlow. However, the unit test will fail as the stateFlow doesn't seem to get updated.
I think its because the test will finish ...
6
votes
4
answers
4k
views
How to init a sealed-class in MutableStateFlow
I have a sealed-class like this
sealed class LoadState {
class Loading : LoadState()
class Success : LoadState()
class Fail : LoadState()
}
I use sealed-class with LiveData, it works
open ...
6
votes
2
answers
5k
views
Best practice when using mutableState with jetpack compose inside viewmodel with exposing mutable state
I have the following ViewModel
@HiltViewModel
class ShareViewModel @Inject constructor(
private val taskRepository: TaskRepository
): ViewModel() {
private val searchAppBarStateMutableState: ...
6
votes
3
answers
7k
views
How to properly use StateFlow with Jetpack compose?
I'm doing a API call in the ViewModel and observing it in the composable like this:
class FancyViewModel(): ViewModel(){
private val _someUIState =
MutableStateFlow<FancyWrapper>(...
6
votes
3
answers
4k
views
MutableStateFlow not working with MutableList
Here is my MutableStateFlow value I try to work with:
val songList: MutableStateFlow<MutableList<Song>> = MutableStateFlow(arrayListOf())
I need to observe changes (after methods like add,...
6
votes
3
answers
4k
views
flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) doesn't stop flows while App is in background
I'm trying to observe the result of the View Collection and upstream flows stopped.
But viewModel.testFlow is still collecting while the App is in the background.
Why can't I observe the collection is ...
5
votes
6
answers
8k
views
How to avoid default value in MutableStateFlow kotlin
I am using MutableStateFlow in my project. When we initialise the MutableStateFlow object we need to give default value.
val topics = MutableStateFlow<List<String>>(emptyList())
when I ...
5
votes
1
answer
2k
views
How to print size of flow in kotlin
Hey I am new in kotlin flow. I am trying to print flow size. As we know that list has size() function. Do we have something similar function for flow.
val list = mutableListof(1,2,3)
println(list.size)...
5
votes
1
answer
4k
views
Flow emits different values when collecting it multiple times
I created a Flow from which I emit data. When I collect this flow twice, there are 2 different sets of data emitted from the same variable instead of emitting the same values to both collectors.
I ...
5
votes
2
answers
2k
views
Android collectAsStateWithLifecycle() not collecting inside composable
I am using compose LazyColumn with viewModel updating the list items by having inside my viewModel:
data class ContactsListUiState(
val contacts: MutableList<Contact>
)
@...
5
votes
1
answer
2k
views
Jetpack compose lazy column not recomposing with list
I have a list which is stored inside a Viewmodel via Stateflow.
class FirstSettingViewModel : ViewModel() {
private val _mRoomList = MutableStateFlow<List<InitRoom>>(mutableListOf())
...
5
votes
2
answers
2k
views
Update Kotlin StateFlow without change emitting
Is it possible to update Kotlin StateFlow without emitting the change?
The use case is that when user zooms a chart view, I would like to have that restored when activity resumes but skip the ...
5
votes
1
answer
2k
views
A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
Please help for the build error.
Kotlin version : 1.5.31
Gradle-zip: 7.2
Gradle version: 7.0.3
Execution failed for task ':app:mergeDebugJavaResource'.
A failure occurred while executing com.android....
5
votes
0
answers
567
views
Jetpack Compose navigation state doesn't restore
I'm struggling with the Jetpack Compose navigation. I'm following the NowInAndroid architecture, but I don't have the correct behaviour. I have 4 destinations in my bottomBar, one of them is a Feed-...
5
votes
0
answers
1k
views
StateFlow triggers multiple times when used to navigate to other Composable
I have been using StateFlow + sealed interfaces to represent the various UI states in my Android app. In my ViewModel I have a sealed interface UiState that does this, and the various states are ...
5
votes
2
answers
3k
views
LiveData Transformation to StateFlow / SharedFlow
What is the equivalent code for this live data transformation in StateFlow / SharedFlow?
val myLiveData: LiveData<MyLiveData> = Transformations
.switchMap(_query) {
...
4
votes
3
answers
13k
views
why flow collect call more than twice in kotlin?
Hey I am working in kotlin flow in android. I noticed that my kotlin flow collectLatest is calling twice and sometimes even more. I tried this answer but it didn't work for me. I printed the log ...
4
votes
1
answer
2k
views
Problem with Jetpack Compose Navigation and StateFlow
The Composable function Application creates a NavHostController which defines 2 targets. A StartScreen and a ContentScreen. The StartScreen has just a single button, which triggers a simulated backend ...
4
votes
1
answer
4k
views
Unlike Livedata, using Flow in Room query doesn't trigger a refresh when updating a table entry but works if I delete or insert an entry
When using Livedata as a return type for a select* query on a table in Room, then I observe on it, I get triggers if I update/insert/delete an entry in that table. However, when I tried using Kotlin ...
4
votes
1
answer
1k
views
How many Stateflows can I observe at one time?
I develop apps for Android. I was wondering how many Kotlin Stateflows can I observe at one time? Every observe that I do is done on different CoroutineScope created by myself, dispatched by IO ...
4
votes
2
answers
1k
views
How to cancel a combine of flows when one of them emits a certain value?
I am doing multiple network requests in parallel and monitoring the result using a Stateflow.
Each network request is done in a separate flow, and I use combine to push the latest status on my ...
4
votes
4
answers
4k
views
Kotlin Coroutine/Flow Timeout without cancelling the running coroutine?
I am trying to create a Flow that emits a value after a timeout, without cancelling the underlying coroutine. The idea is that the network call has X time to complete and emit a value and after that ...
4
votes
0
answers
793
views
How to map StateFlow values and pass it to view via databinding
I have a StateFlow that I want to use with Android data binding. As values in the flow I use a sealed type:
data class State(
val idState: IdState
) : UiState
sealed class IdState {
object ...
4
votes
1
answer
1k
views
StateFlow: Cancellation of Older Emitted State After Collecting
I m relatively new in kotlin flows and I m creating the Login Module using Flows in android. I have been stuck from past few days in flows as I m collecting it in ViewModels but I m facing problem ...
3
votes
2
answers
4k
views
jetpack compose stateflow not refreshing list
In my project, I have two fragments.
One is a normal fragment, and another is a bottomSheetDialogFragment.
In my normal fragment, I have a lazyColumn.
I would like to do some settings in the ...
3
votes
2
answers
1k
views
Suspending until StateFlow reaches one of the desired states and returning the result
Consider a sealed class State.
sealed class State {
object Unknown : State()
object Loading : State()
object Success : State()
data class Failure(val exception: Exception)
}
I have a ...
3
votes
1
answer
1k
views
Flow.stateIn() not receiving new value from it's source
I tried to combine several SharedFlow into one StateFlow using stateIn. But my StateFlow seems not updating after I emit new value to it's SharedFlow source. I found out that the problem is from how I ...
3
votes
3
answers
3k
views
Compose LazyColumn key, messes up scrolling when sorting the items
I'm trying to implement simple sort with items that are in a state.
This will work perfectly, only problem is that the animation is now gone, because it doesn't have a key.
LazyColumn(
state = ...
3
votes
1
answer
1k
views
MutableStateFlow events being overwritten
In MyViewModel a MutableStateFlow is used to transmit events to the fragment.
When the value of the MutableStateFlow is changed the earlier values are being overwritten inside the coroutine. So never ...
3
votes
1
answer
2k
views
How to send Kotlin Flow events into existing Flow stream via combine?
I have two flows.
flow1() emits a stream of integers every second.
flow2() emits an integer when a button is clicked.
Both flows are combined with combinedFlows() and the combined results are ...