I need to make a function call which does not return anything (void
). Only way to get notified about function completion is sending a callback
function.
Now I an using BLoC
pattern along with ReDux
, When an event is dispatched, I dispatch another action to store of redux
, After action
is completed it calls the callback
function. And now inside callback
function, I want to update the state
of bloc
. Below is my implementation,
if (event is Login) {
yield currentState.copyWith(formProcessing: true);
store.dispatch(authActions.login(
currentState.username,
currentState.password,
(error, data) {
print(error);
print(data);
// I want to yield here.
yield currentState.copyWith(formProcessing: false);
},
));
}
As shown in the above code snippet, Inside the callback function, I want to yield
.
Solution
Create a function that returns the future and makes callback function to store dispatch, Heres sample.
if (event is Login) {
yield currentState.copyWith(formProcessing: true);
try {
dynamic result = await loginAction(store, currentState.username, currentState.password);
print(result);
yield currentState.copyWith(formProcessing: false);
} catch (e) {
print(e);
}
}
Future loginAction(store, username, password) {
var completer = new Completer();
store.dispatch(authActions.login(
username,
password,
(error, data) {
if (error != null) {
completer.completeError(error);
} else if (data != null) {
completer.complete(data);
}
},
));
return completer.future;
}