https://kotlinlang.org logo
#flow
Title
# flow
o

Osman Saral

10/06/2023, 9:06 AM
I'm trying to implement a timeout mechanism on a suspend function which returns a
SharedFlow
. I was launching a coroutine using
CoroutineScope(coroutineContext).launch { }
but I've read that it's not a goo practice. It's suggested to make function a
CoroutineScope
extension instead. But it's necessary for me to make that function suspend. How can I implement a timeout mechanism for a suspend function which needs to return the flow?
This is the simplified version of my implementation:
Copy code
class Client {
    sealed interface State {
        object Loading: State
        object Success: State
        object Error: State
    }

    interface MyCallListener {
        suspend fun onResult(result: State)
    }

    var methodListener: MyCallListener? = null

    suspend inline fun call(): SharedFlow<State> {

        val flow = MutableSharedFlow<State>()

        //onResult is called elsewhere. this way, it's possible to emit a result to the flow
        methodListener = object : MyCallListener {
            override suspend fun onResult(result: State) {
                flow.emit(result)
            }
        }

        flow.tryEmit(State.Loading)

        CoroutineScope(coroutineContext).launch {
            var latestValue: State? = null
            launch {
                flow.collect {
                    latestValue = it
                }
            }
            delay(5000)
            if (latestValue is State.Loading) {
                flow.emit(State.Error)
            }
        }

        return flow
    }
}
I need to call that function from another suspend function:
Copy code
class MyUseCase(
    val client: Client
) {
    suspend fun foo() = client.call()
}
This currently works but since it's not recommended to use
CoroutineScope(coroutineContext)
and I cant use
CoroutineScope
extension, is there a better way to do this?