Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last item emited by a Flow and dont receive updates

What is the best way to obtain the last element emitted by a flow without receiving updates.

Question: I use a flow to observe changes in certain shared preferences, but sometimes I want to know the current value of that preference. I always use two functions, one to observe the values in a flow and the other to capture the data directly, is there any way to archive the same behavior with just the observer function?

suspend fun getBreadcrumb(): Breadcrumb =
        withContext(Dispatchers.IO) context@ {
            ...
        }

fun observeBreadcrumb(): Flow<Breadcrumb> {
        ....
    }
like image 707
cmpeguerog Avatar asked Jan 25 '26 15:01

cmpeguerog


1 Answers

Consider using StateFlow

StateFlow is a new API that was recently added to the coroutines standard library. You can consume it like a regular flow, but it also has a value property that gets the most recent value.

At the moment, the only way to send a new value to a state flow is to update its value property. You can't yet turn a regular flow into a state flow, though there is an open proposal for it.

Let's say you send values to the flow like this:

val breadcrumbs = MutableStateFlow(someValue)

launch {
    while (isActive) {
        waitForSomeCondition()
        breadcrumbs.value = getLatestValue()
    }
}

You can retrieve the latest value whenever you want, for example like this:

launch {
    while (isActive) {
        delay(1000)
        println("Current value is ${breadcrumbs.value}")
    }
}

But you can also collect it like a regular flow, and receive the new value each time it changes:

launch {
    breadcrumbs.collect {
        println("Current value is ${it}")
    }
}

This is an experimental API, so there are likely to be improvements and changes down the line.

like image 55
Sam Avatar answered Jan 27 '26 05:01

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!