OneMap

OneMap

  • This function takes two generic types: T (the type of data held by the Resource) and R (the type of data after transformation).

  • It accepts a lambda function transform that takes a value of type T and returns a value of type R.

  • It then uses a when expression to handle different states of the Resource:

    • Success: If the Resource is successful, it applies the transform function to the data and creates a new Resource.Success with the transformed data of type R.

    • Failure: If the Resource has failed, it creates a new Resource.Failure with the original error message.

    • Loading, Default, Empty: It simply creates a new Resource of the same type (Loading, Default, or Empty) without modifying the state.

Usage:

override suspend fun getDetailMovie(id: Int): Flow<Resource<MovieDetail>> {
    return repository.getDetailMovie(id).map { resource ->
        resource.oneMap { response -> response.toDomain() }
    }
}

OneMapList

  • This function is similar to oneMap but specifically designed for Resource<List<T>>.

  • It transforms a list of data within the Resource.

  • It uses the map function on the data list to apply the transform function to each element and create a new list of transformed data (List<R>)

  • Similar to oneMap, it handles different states of the Resource using a when expression.

Usage:

override suspend fun getList(): Flow<Resource<List<FirestoreData>>> {
    return repo.getList().map { resource ->
        resource.oneMapList { data -> data.toDomain() }
    }
}

This example shows how to use oneMapList to transform a list of strings within a Resource to uppercase. You can use oneMap in a similar way for other data types.

These extension functions promote cleaner code by avoiding repetitive checks for resource state and transforming data within the Resource type itself.

Last updated