NickJokic / flutter-blocs-at-scale

7 stars 0 forks source link

Information regarding BLOCs and returning both `T` and `List<T>` #3

Open Peterkrol12 opened 1 year ago

Peterkrol12 commented 1 year ago

I am looking at the scalable BLOC implementation you described in your articles and tried using it. I really like that it simplifies the states and events, as onboarding and maintaining will be noticeably easier. However, I have a question regarding the generic type of the RemoteDataBloc.

Basically, how would you go about a BLOC which can both return a list of users, and just a single instance of a user?

Would you implement two separate BLOCs, one returning List<T> and one returning T? Or would you return a UserPage for both cases, but with the single instance return with a size of 1?

Curious what you think about it, as I am not sure what the best solution would be.

mradzinski commented 1 year ago

I would personally keep a single BLoC that returns a List<T>. Here's an example:

/// Returns a list of users based on the received user ids. 
/// The returned list can have the same count, or less than the received list of user ids 
/// depending on the existence of those users
///
/// This function will not throw an error if none of the user ids exists, 
/// but instead return an empty list.
List<T> getUsers(List<String> userIds) {...}

First of all: Documentation of the function. Based on it, If the implementor decides to pass 1 single identifier, then (assuming the user exists) it will get 1 single user. On the other hand, if the implementor decides to pass N identifiers, it will get N users.

I normally tend to favor functions which accepts lists and return lists, and –whenever it makes sense– I tend to avoid writing a getSingleXXX function. The reason for this is due to flexibility and maintainability. Instead of having 2 functions to maintain, now you only have 1 function that works for all the scenarios and that it's responsibility is clearly documented. #KISS

Peterkrol12 commented 1 year ago

Thanks for taking the time to respond!

This is an approach I (and I think 'we' as a team) haven't thought off. Removes a lot of complexity regarding the states throughout the app. Our API is currently restful, so that would require some adapting. For example, we would have a 'getAll' call which doesn't require a list of ids, so that would mean the userIds list is empty and should therefore call the 'getAll' endpoint from the API. Our use case would probably benefit in the same way by just using String? userId as parameter. If userId is given, execute the 'getSpecific' call.

As we are still not sure which approach to choose regarding state management, I will for sure bring this up in our meetings.

Either way, I'll think about this more the coming days, thanks a lot!