Skip to content

Instantly share code, notes, and snippets.

@lbv
Created May 8, 2019 15:43
Show Gist options
  • Save lbv/786521ed1ac7afe8741875ddb67691c6 to your computer and use it in GitHub Desktop.
Save lbv/786521ed1ac7afe8741875ddb67691c6 to your computer and use it in GitHub Desktop.
import 'package:bloc/bloc.dart';
class SomeState {
final bool isLoading;
final int data;
SomeState({this.isLoading = false, this.data = 0});
SomeState copyWith({bool isLoading, int data}) {
return SomeState(
isLoading: isLoading ?? this.isLoading,
data: data ?? this.data,
);
}
@override
String toString() => 'SomeState { isLoading: $isLoading, data: $data }';
}
Future<int> slowComputation(int input) async {
return Future.delayed(Duration(seconds: 5), () {
return input + 1;
});
}
class MyBloc extends Bloc<String, SomeState> {
@override
SomeState get initialState => SomeState();
@override
Stream<SomeState> mapEventToState(String event) async* {
yield currentState.copyWith(isLoading: true);
try {
int result = await slowComputation(currentState.data);
yield currentState.copyWith(data: result);
}
finally {
yield currentState.copyWith(isLoading: false);
}
}
}
void main() {
final bloc = MyBloc();
bloc.dispatch('something');
bloc.state.forEach((state) {
print('State received: $state');
});
}
@lbv
Copy link
Author

lbv commented May 8, 2019

Output:

$ dart lib/main.dart
lib/main.dart:1: Warning: Interpreting this as package URI, 'package:bloc_ex/main.dart'.
State received: SomeState { isLoading: false, data: 0 }
State received: SomeState { isLoading: true, data: 0 }
State received: SomeState { isLoading: true, data: 1 }
State received: SomeState { isLoading: false, data: 1 }

@smiLLe
Copy link

smiLLe commented May 8, 2019

try this instead

@override
  Stream<SomeState> mapEventToState(String event) async* {
    yield* _event();
  }

  Stream<SomeState> _event() async* {
    yield currentState.copyWith(isLoading: true);
    try {
      int result = await slowComputation(currentState.data);
      yield currentState.copyWith(data: result);
    } finally {
      yield currentState.copyWith(isLoading: false);
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment