Search code examples
kotlinoperatorskotlin-flow

Flow.take(ITEM_COUNT) returning all the elements rather then specified amount of elements


I've a method X that's getting data from the server via pub sub. This method returns a flow. I've another method that subscribes to the flow by method X but only wants to take the first 3 values max from the flow if the data is distinct compared to previous data. I've written the following code

fun subscribeToData() : Flow<List<MyData>> {
    ....
    //incoming data
    emit(list)
}

fun getUptoFirst3Items() {
   subscribeToData()
   .take(ITEM_COUNT) // ITEM_COUNT is 3
   .distinctUntilChange() //only proceed if the data is different from the previous top 3 items
   .mapIndex {
     //do transformation
   }
   .collect { transformedListOf3Elements ->
    
   }

}

Problem:

In collect{} I'm not getting 3 elements but rather I'm getting all the data that's coming in the flow.

I'm not sure what's wrong here? Can someone help me?


Solution

  • You have a Flow<List<MyData>> here, which means every element of this flow is itself a list.

    The take operator is applied on the flow, so you will take the 3 first lists of the flow. Each individual list is not limited, unless you use take on the list itself.

    So the name transformedListOf3Elements is incorrect, because the list is of an unknown number of elements, unless you filter it somehow in the map.