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

ursus

02/28/2024, 7:18 PM
Copy code
fun <T : Any> Flow<T?>.validate( validator: (T) -> Status): Flow<Status> =
    distinctUntilChanged()
        .transformLatest {
            val valueAndMetadata = it ?: return@transformLatest <--------------
            emit(Pending)
            delay(500)
            val status = withContext(Dispatchers.Default) { <------------
                validator(valueAndMetadata)
            }
            emit(status)
        }
can anyone double check this? is the usage of
withContext
in a
transformLatest
operator to offload a synchronous calculation correct? I faintly remember someone complaining about switching dispatchers manually in flow operators
c

CLOVIS

02/29/2024, 8:58 AM
What are you trying to do? Switching dispatchers is risky because you can't
emit
from other dispatchers. In this case, you switch temporarily but go back to the original dispatcher before emitting, so I believe it's fine (but I'm no expert)
Instead of
val valueAndMetadata = it ?: return@transformLatest
I would just use
.filterNotNull()
before the
transformLatest
u

ursus

02/29/2024, 12:13 PM
that would not unsubscribe the previous transformLatest
i have there heavy regexes which take a few ms, so nkt suitable for main thread
2 Views