Emit Flow values when the block is inside Runnable body

Viewed 784

So I have this function where I can emit values with flow but I need to send values periodically and so I used:

fun hereIsAFunction(): Flow<Type> = flow {
    Handler.postDelayed({
        //This is in Runnable and I can't emit values
        emit(value) //Error 'Suspension function can only be called within Coroutine body
    }, 1000)

    usingOtherFunction()
}

I don't want to block the function 'usingOtherFunction()', that's why I'm using a runnable

Question: Is there any way to emit values with Flow with periodically events? If yes, what should I look into?

2 Answers

According to your comment that you want to do something in parallel, you can launch 2 coroutines in a scope. They will run independent to each other:

fun hereIsAFunction(): Flow<Type> = flow {
    coroutineScope {
        launch {
            (0..100).forEach {
                delay(1000)
                emit(...)
            }
        }
        launch {
            usingOtherFunction()
        }
    }
}
Related