How do I split Kotlin flow by some property of flowed objects

Viewed 27

Imagine we have an old good CRUD service over some User entity. We also have kind of event-driven system and we want to emit UserUpdated event every time when User is updating. Event object contains an userId: Int property.

On the event listener side we want to protect our system from event spamming. As far as I know, the most straightforward way to do this in Kotlin is to pass all event through flow with debounce operator. Now I guess if we get 10 events during 1 second we will pass to processing only the last one.

    flow
        .debounce(1000)
        .onEach { doSmthWithEvent(...) }
        .launchIn(coroutineScope)

But we don't want to debounce all events indiscriminately. We want to debounce only events related to particular userId. First thing that comes to my mind is to have a dedicated flow for each userId. But since we can have a hundreds of users we will have a hundreds of flows in memory. Flows are lightweight but anyway it looks too bruteforce-ish.

So the question is are there any ways to kind of split a single flow by some event property into subflows and to apply debounce to this new subflow? Something like that

    flow
        .debounceBy(1000) { it.userId }
        .onEach { doSmthWithEvent(...) }
        .launchIn(coroutineScope)
1 Answers

I guess you can filter users by particularId and then use debounce if I correctly understand your issue:

flow
    .filter { it.userId == particularId }
    .debounce(1000)
    .onEach { doSmthWithEvent(...) }
    .launchIn(coroutineScope)
Related