Hello all! I’m working with grpc and kotlin in a s...
# grpc
j
Hello all! I’m working with grpc and kotlin in a spring-boot project. Do you know if there is a way of putting a deadline (per flow element and not entire request, if this makes sense) on a grpc client when calling a stub that returns a kotlin.flow?
w
Is my interpretation of you question correct? You want the the client to give up receiving if any two elements are separated by more than a given duration?
j
Kind of 😊 My initial problem was that the server was not reponding and by default there is no time out, so the function call just blocked forever. Then I noticed that the return type is a flow so I was thinking that perhaps I should not put a timeout of a few seconds because the flow might not be finished. I was asking about deadlines because I wasn't able to find timeouts in config. Thanks in advance for any feedback!
w
I wrote this function which will cancel a flow if an element is not received at least every `deadline`:
Copy code
fun <T> Flow<T>.withElementDeadline(
  deadline: Duration
): Flow<T> = channelFlow {
  var cancelJob: Job? = null
  onEach {
    cancelJob?.cancel()
    cancelJob = launch {
      delay(deadline)
      this@channelFlow.cancel("More than $deadline between elements")
    }
  }
    .collect { send(it) }
}
This has nothing to do with gRPC, but would allow your client to cancel the flow (which should cancel the call on the server as well) and retry if there is a long gap between elements.
🙌 1
You can test it with something like this:
Copy code
suspend fun main() {
  flow {
    while (true) {
      val delay = Random.nextLong(100, 550).milliseconds
      println("Dealy: $delay")
      delay(delay)
      emit(delay)
    }
  }.withElementDeadline(500.milliseconds)
    .collectIndexed { index, value -> println("RX: $index: $value") }
}
j
Many thanks, will try it soon!
137 Views