5

I'm using the BLoC pattern for state management in my Flutter app and I've used these two methods to manage state data.e

1. making each piece of data have its own stream and using StreamBuilder for each widget that needs the data in the UI 

    class LoginBloc{
      bool _isLoggedIn;
      String _username;
      String _password;


      final _isloggedInSubject = BehaviorSubject<bool>();
      StreamSink<bool> get isLoggedInSink => _isloggedInSubject.sink;

      final _usernameSubject = BehaviorSubject<String>();
      StreamSink<String> get userNameSink => _usernameSubject.sink;
      //... //same for the other states

      bool login(){
        _service.Login(_usernameSubject.value,...);
      }
    }

2. Wrapping all page state in a view model and then making just one stream of that viewmodel

    class LoginBloc{
      final loginPageSubject = BehaviorSubject<LoginPageState>();

      bool login(){
        _service.Login(loginPageSubject.value.username, loginPageState.value.password);
      }

    }

    class LoginPageState{
      bool isLoggedIn;
      String username;
      String password;

      LoginPageState({this.isLoggedIn, this.username, this.password});

    }

I believe Option 1 would work like this. only the widgets using that stream in their streambuilder would be rebuilt if the stream changes. Option two however means that all widgets that shares the same state would rebuilt even though the property they are tied to in the state did not change, they would all be rebuilt as a side effect of manipulating the LoginPageState object and re-adding it into the stream via the _loginPageSubject.sink.

Option 1 seems to involve a lot of code should you have plenty state data a lot of (plenty BehaviorSubjects and Observables) compared to option 2 which only needs one BehaviorSubject to manage all the state contained in just one state object. Is there a performance gain to using one option over the other?

ibnhamza
  • 861
  • 1
  • 15
  • 29

0 Answers0