Skip to content
This repository has been archived by the owner on Jul 9, 2020. It is now read-only.

CubitListener behaviour skips(1) #36

Closed
Manuelbaun opened this issue Jul 1, 2020 · 5 comments
Closed

CubitListener behaviour skips(1) #36

Manuelbaun opened this issue Jul 1, 2020 · 5 comments
Assignees
Labels
question Further information is requested
Projects

Comments

@Manuelbaun
Copy link

Hi Felix,

I have a question to the CubitListener: Why does the subscribe method skips the first state?

/// cubit_listener.dart
  void _subscribe() {
    if (_cubit != null) {
      _subscription = _cubit.skip(1).listen((state) {
        if (widget.condition?.call(_previousState, state) ?? true) {
          widget.listener(context, state);
        }
        _previousState = state;
      });
    }
  }

I am using an AuthCubit and AuthState with freezed like here

@freezed
abstract class AuthState with _$AuthState {
  const factory AuthState.initial() = Initial;
  const factory AuthState.authenticated() = Authenticated;
  const factory AuthState.unauthenticated() = Unauthenticated;
}

@injectable
class AuthCubit extends Cubit<AuthState> {
  final IAuthFacade _authFacade;
  AuthCubit(this._authFacade) : super(const AuthState.initial());

  void checkIfAuthenticated() async {
    final userOption = await _authFacade.getSignedInUser();

    final nextState = userOption.fold(
      () => const AuthState.unauthenticated(),
      (a) => const AuthState.authenticated(),
    );

    emit(nextState);
  }

  void signOut() async {
    await _authFacade.signOut();
    emit(const Unauthenticated());
  }
}

and I got a Splashscreen Widget like here:

class SplashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CubitListener<AuthCubit, AuthState>(
      cubit: getIt<AuthCubit>(),
      listener: (context, state) {
        state.map(
          initial: (_) {
             // do nothing and spin the progress indicator until
             // state is either authenticated or unauthenticated
          },
          authenticated: (_) {
            // todo: navigate to dashboardPage
          },
          unauthenticated: (_) {
            ExtendedNavigator.of(context).pushReplacementNamed(Routes.signInPage);
          },
        );
      },
      child: Scaffold(body: Center(child: CircularProgressIndicator())),
    );
  }
}

So now to my Problem:

When I listen to the Cubit with CubitListener, the CubitStream first yields the current state, then it will yield all controller stream states. But in the CubitListener, the first yield will be skipped and this causes the problem, that the listener method of the CubitListener will not be called when the widget is built for the first time.

In this case, I am not able to either navigate to the dashboardPage, if the state is 'Authenticated' nor to the signInPage if I am 'Unauthenticated'.

Obviously, if the widget is built and I emit a state not equal to the last state then, then the listener method is called, and I can to whatever I need.

Maybe, we could have an option, if we want to skip the first yielded state?

@narcodico
Copy link

Hi @Manuelbaun 👋

The listener is by design implemented in such a way that it will only react to state changes after it is mounted into the tree, since it doesn't make sense to react to the last known state since that might be obsolete by the time the listener subscribes to the stream of states.

Your issue raises from your architecture. Your CubitListener<AuthCubit, AuthState> should be placed globally instead of scoping it to your splash screen, because you always want it to be ready to react to state changes in your authentication.
A good place to provide it would be inside MaterialApp's builder.
You can check out this example and adapt it to cubit.

Hope it helps 👍

@Manuelbaun
Copy link
Author

HI @RollyPeres,
yes, you are right, it makes totally sense now. I also found out, that when I would change the skip to 0, then I get another undesigned behavior, in the sign-in/signout flow. So it must be some architecture-related issues.

Thanks for pointing it out. I will look into the example you've posted. Since I am also using the Auto_route package, I will have to look at how I can make it work together.

@Manuelbaun
Copy link
Author

I looked into the example and I could refactor authentication as you suggested and provided it to the builder in the MaterialApp.
However, the example uses bloc with the async event dispatch, but Cubit uses methods (sync).

But the issue remains:
I need to call the method checkIfAuthenticated of the AuthCubit after the CubitListener listens to the AuthCubit. Then the listener would be triggered properly and I can navigate to another page.

But currently, there is no way, to find out, when the CubitListener is mounted to the tree. So if call the checkIfAuthenticated method just before its mounted, then I will not be able to navigate to another page.

I could use a time delay, but it a dirty hack and potential for a race condition.

Do you have an idea of how I can manage that?

@felangel felangel added the question Further information is requested label Jul 1, 2020
@felangel felangel added this to To do in cubit via automation Jul 1, 2020
@felangel
Copy link
Owner

felangel commented Jul 1, 2020

Hi @Manuelbaun 👋
Thanks for opening an issue!

Cubit is still async and this isn't specific to cubit (you can have a race-condition with listeners with bloc as well). I would highly recommend lifting your listener up in the widget tree to be above where the method is called. That guarantees the listener is mounted before anything has happened.

If you're still having trouble, it would be great if you could share a link to a sample github repo which illustrates the problem you're having. Thanks! 👍

@felangel felangel closed this as completed Jul 1, 2020
cubit automation moved this from To do to Done Jul 1, 2020
@felangel felangel self-assigned this Jul 1, 2020
@narcodico
Copy link

I've created a quick sample to illustrate this common request, maybe others will also find it useful.

You can check it out here 🎉

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
question Further information is requested
Projects
No open projects
cubit
  
Done
Development

No branches or pull requests

3 participants