```fun <T : Any> Flow<T?>.validate( validator: (T)...
# coroutines
u
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
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
that would not unsubscribe the previous transformLatest
i have there heavy regexes which take a few ms, so nkt suitable for main thread