FilledStacks / flutter-tutorials

The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.
MIT License
4.75k stars 1.76k forks source link

viewmodels - bloc pattern resemblance. #25

Closed elhe26 closed 5 years ago

elhe26 commented 5 years ago

Hi @FilledStacks ,

I'm wondering if the approach used in the architecture you proposed resembles the bloc pattern.

For example, this code is using the bloc pattern:

class SignInBloc {
  final AuthBase auth;

  SignInBloc({@required this.auth});

  final StreamController<bool> _isLoadingController = StreamController<bool>();

  Stream<bool> get isLoadingStream => _isLoadingController.stream;

  void dispose() {
    _isLoadingController.close();
  }

  void _setIsLoading(bool isLoading) {
    if (!_isLoadingController.isClosed) {
      _isLoadingController.add(isLoading);
    }
  }
} 

And your implementation:

class FeedbackViewModel extends BaseModel {
  FirestoreService _firestoreService = locator<FirestoreService>();
  List<UserFeedback> userFeedback;

  FeedbackViewModel() {
    _firestoreService.feedback.asBroadcastStream().listen(_onFeedbackUpdated);
  }

  void markFeedbackAsRead({@required String feedbackId}) {
    _firestoreService.markFeedbackAsRead(feedbackId: feedbackId);
  }

  void _onFeedbackUpdated(List<UserFeedback> event) {
    userFeedback = event;

    if (userFeedback == null) {
      setState(ViewState.Busy);
    } else {
      setState(userFeedback.length == 0
          ? ViewState.NoDataAvailable
          : ViewState.DataFetched);
    }
  }
}

What do you think?

FilledStacks commented 5 years ago

Hey there,

The code definitely resembles each other but the architecture is completely different. In my case the view model uses the stream internally to produce a new state and then notify the view that something has changed.

In the case of BLoC the stream is the sole input and output for the logic component. On my side I can have additional methods of handling the state with multiple output properties and public functions to call.

On the BLoC side you have to go through your sink/event actions pipeline. And I'm not a big fan of "have-to's" . But it does look very similar. If the LoadingController used an enum and you broadcast different values based on some logic like I do it would look even more similar.