[HELP] Emit state from a stream in repository
Supercaly opened this issue ยท 2 comments
Supercaly commented
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?
narcodico commented
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 ๐
Supercaly commented
Thanks, it's exactly what I needed ๐ ๐