Created
May 16, 2019 16:12
-
-
Save audkar/abe61f4d32a0db479ddcd2dcb11a9fd3 to your computer and use it in GitHub Desktop.
Flutter EventChannel onCancel is not called on Activity destroy
This file contains 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 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
LongRunningPlugin _plugin = new LongRunningPlugin(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: StreamBuilder( | |
initialData: "0", | |
stream: _plugin.getIt, | |
builder: (context, snapshot) => | |
Text('Non-canceled tasks: ${snapshot.data}'), | |
), | |
), | |
); | |
} | |
} | |
class LongRunningPlugin { | |
final EventChannel channel = EventChannel("long_running_plugin"); | |
Stream get getIt => channel.receiveBroadcastStream(); | |
} |
This file contains 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
public class MainActivity extends FlutterActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
LongRunningTaskPlugin plugin = new LongRunningTaskPlugin(); | |
EventChannel channel = new EventChannel(getFlutterView(), "long_running_plugin"); | |
channel.setStreamHandler(plugin); | |
} | |
static class LongRunningTaskPlugin implements EventChannel.StreamHandler { | |
@Override | |
public void onListen(Object args, EventChannel.EventSink eventSink) { | |
Log.i(TAG, "onListen"); | |
eventSink.success(++counter); | |
} | |
@Override | |
public void onCancel(Object args) { | |
Log.i(TAG, "onCancel"); | |
counter--; | |
} | |
private static int counter = 0; | |
private static final String TAG = "LongRunningTaskPlugin"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment