felangel/cubit

[HELP] Emit state from a stream in repository

Supercaly opened this issue ยท 2 comments

Hi, I've used a lot your Bloc package and I'm trying this for the first time, so I've some questions about data management with a repository.
In my code, I've got a repository with a method getStream witch returns a stream of data.
My Cubit is structured like this:

class TestCubit extends Cubit<TestState> {
   final TestRepo repo = TestRepo();
   TestCubit(): super(TestStateLoading());
   
   void fetch() {
      var newState = ...
      emit(newState);
   }
}

How can I convert the value from each value of the stream to the new state?

Hi @Supercaly ๐Ÿ‘‹

Here's how you can achieve that:

class TestCubit extends Cubit<TestState> {
  TestCubit({@required TestRepo testRepo})
      : assert(testRepo != null),
        _testRepo = testRepo,
        super(TestStateLoading());

  final TestRepo _testRepo;

  StreamSubscription _sub;

  void fetch() {
    _sub?.cancel();
    _sub = _testRepo.getStream.listen((data) {
      emit(TestStateLoaded(data));
    });
  }

  @override
  Future<void> close() {
    _sub?.cancel();
    return super.close();
  }
}

Hope it helps ๐Ÿ‘

Thanks, it's exactly what I needed ๐Ÿ˜„ ๐Ÿ‘