https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tower Guidev2

09/07/2021, 7:34 AM
Hi, I am investigating Kotlin Flows (On Android with Room/Sqlite DB)
I have a requirement where I need to consume a
Flow
Once then "disable" it. I have a Room database table where I have status values per "Action". The status can be
SUCCESS
,
EMPTY
,
FAILURE
each status row has an
ARCHIVED
column that is either true or false. The DB table resembles this
Copy code
data class OutcomeDO(
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "outcome") val outcome: Outcome,
    @ColumnInfo(name = "archived") val archived: Boolean = false,
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "result_local_id")
    var resultLocalId: Long = 0L
}
My DAO resembles this
Copy code
@Query("SELECT * from result_table WHERE name = :name AND archived = :archive")
fun fetch(name: String, archive : Boolean = false): Flow<OutcomeDO>
I query this table like this:-
Copy code
return database.outcomeDAO().fetch(name = Fred::class.java.name).filterNotNull().flatMapLatest { flowOf(it.outcome) }
and consume the Flow like this:-
Copy code
outcome.take(1).collect { outcome ->
    when (outcome) {
        Success -> // display data
        Empty -> {
            showError(anchorView, R.string.no_data_found)
        }
        Failure -> {
            showError(anchorView, R.string.data_search_failed)
        }
    }
}
Once the flow has been consumed in the above snippet I wish to set that particular row on the underlying database to
ARCHIVED
= true How can I achieve this? Is there a Flow operator such as OnCompletion/OnConsumed that I can employ to detect when the flow has been consumed and allow me to update a specific row on my DB table?
or how can I tell when a Flow has already been collected?
j

Joffrey

09/08/2021, 6:46 AM
There is indeed
onCompletion
that you can add when you create the flow to detect the end of the collection (normally or exceptionally)
20 Views