Skip to content

Commit

Permalink
feat: Add completed future for effects (#3123)
Browse files Browse the repository at this point in the history
This PR adds a `completed` future for effects which completes when the
effect finishes.
  • Loading branch information
ufrshubham committed Apr 14, 2024
1 parent a4a6a6a commit 5e967de
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/flame/effects.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ functionality inherited by all other effects. This includes:
- Optional user-provided `onComplete`, which will be invoked when the effect has just
completed its execution but before it is removed from the game.

- A `completed` future that completes when the effect finishes.

- The `reset()` method reverts the effect to its original state, allowing it to run once again.


Expand Down
13 changes: 13 additions & 0 deletions packages/flame/lib/src/effects/effect.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import 'package:flame/components.dart';
import 'package:flame/src/effects/controllers/effect_controller.dart';
import 'package:meta/meta.dart';
Expand Down Expand Up @@ -75,6 +77,15 @@ abstract class Effect extends Component {
/// currently paused, this call is a no-op.
void resume() => _paused = false;

Completer<void>? _completer;

/// A future that completes when the effect is finished.
Future<void> get completed {
return controller.completed
? Future.value()
: (_completer ??= Completer<void>()).future;
}

/// Restore the effect to its original state as it was when the effect was
/// just created.
///
Expand Down Expand Up @@ -186,6 +197,8 @@ abstract class Effect extends Component {
@mustCallSuper
void onFinish() {
onComplete?.call();
_completer?.complete();
_completer = null;
}

/// Apply the given [progress] level to the effect's target.
Expand Down
17 changes: 16 additions & 1 deletion packages/flame/test/effects/effect_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';

class _MyEffect extends Effect {
_MyEffect(super.controller);
_MyEffect(super.controller) {
completed.whenComplete(() => ++completedCounter);
}

int completedCounter = 0;

double x = -1;
Function()? onStartCallback;
Expand Down Expand Up @@ -68,6 +72,17 @@ void main() {
expect(effect.x, closeTo(1, 1e-15));
});

test(
'Completed future return on complete',
() async {
final effect = _MyEffect(EffectController(duration: 2));
final completer = effect.completed;

effect.update(4);
await expectLater(completer, completes);
},
);

testWithFlameGame(
'removeOnFinish = true',
(game) async {
Expand Down

0 comments on commit 5e967de

Please sign in to comment.