Last active
May 15, 2021 07:56
-
-
Save ova2/d0ebf032e486c3a2e17b22e9e86b3d6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:async'; | |
| import 'package:flutter/foundation.dart'; | |
| /// This class allows request-reply communication over messaging. | |
| class RequestReplyService { | |
| StreamSubscription _subscription; | |
| /// release resources | |
| void dispose() { | |
| _subscription?.cancel(); | |
| } | |
| /// send request and return response object as [Future] | |
| Future<T> execute<T>({ | |
| @required Future<void> Function() request, | |
| @required Stream<T> Function() response, | |
| }) async { | |
| final completer = Completer<T>(); | |
| // close the last subscription which may be open after | |
| // fast subsequent calls of this method | |
| _subscription?.cancel(); | |
| _subscription = response() | |
| .handleError((error) => completer.completeError(error)) | |
| .listen((T data) { | |
| if (!completer.isCompleted) { | |
| completer.complete(data); | |
| } | |
| }); | |
| request(); | |
| return completer.future; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment