In particular use case I'm making a repository call to obtain data in form of Flow.
It's type is:
Flow<Resource<List<Location>>>
Where:
Resource is wrapper class:
sealed class Resource<T>(val data: T? = null, val message: String? = null) { class Loading<T>(data: T? = null): Resource<T>(data) class Success<T>(data: T?): Resource<T>(data) class Error<T>(message: String, data: T? = null): Resource<T>(data, message)}
Location is my data model class
Each location has it's own property like type. When user switch to section where type's Hotel, use case method is triggered, api call is made and I'm filtering list so that it contains only desirable items.
However the problem is filtering mechanims which doesn't work.
return repository.getLocations()
.onEach { result ->
if (result.data != null) {
when (locationType) {
is LocationType.All -> result.data
is LocationType.Hotel -> result.data.filter { it.type == "Hotel" }
is LocationType.Explore -> result.data.filter { it.type == "Explore" }
is LocationType.Active -> result.data.filter { it.type == "Active" }
is LocationType.Restaurant -> result.data.filter { it.type == "Restaurant" }
}
}
}
Final list isn't changed despite filtering with use ofonEach
UPDATE
The return type of repository call is:
Flow<Resource<List<Location>>>
SOLUTION
Finally I've come up with the solution.
In my use case I'm collecting the flow and inside collect
lambda, I've put code responsible for filtering.
When everything is done I'm just emitting data further ;)
operator fun invoke(
locationType: LocationType
) = flow {
repository.getLocations().collect { result ->
if (result.data != null) {
when (locationType) {
is LocationType.All -> result.data
is LocationType.Hotel -> result.data.filter { it.type == "Hotel" }
is LocationType.Explore -> result.data.filter { it.type == "Explore" }
is LocationType.Active -> result.data.filter { it.type == "Active" }
is LocationType.Restaurant -> result.data.filter { it.type == "Restaurant" }.also { res ->
when (result) {
is Resource.Success -> {
emit(Resource.Success(data = res)) }
is Resource.Loading -> {
emit(Resource.Loading(data = res))
}
is Resource.Error -> {
emit(Resource.Error(data = res, message = result.message ?: ""))
}
}
}