In this code i have a simple riverpod
provider which that should connect and listen to events. here connect to pusher work fine and i can receive data from that and printing in logcat
, but i can't listen to that in defined provider into screen
final pusherProvider= ChangeNotifierProvider<PusherController>((ref) => PusherController.instance
..setEventName('my-event')
..setChannelName('my-channel')
..initPusher()
..connectPusher());
in this screen ref.watch(pusherProvider)
doesn't work
screen class:
@override
Widget build(BuildContext context, WidgetRef ref) {
final pusher = ref.watch(pusherProvider).eventStream;
debugPrint('received!!!!');
PusherController
class:
class PusherController extends ChangeNotifier{
static final PusherController _pusherController = PusherController._();
PusherController._();
static PusherController get instance => _pusherController;
late PusherClient pusher;
late Channel channel;
final StreamController<String> _eventData = StreamController<String>.broadcast();
Sink get _inEventData => _eventData.sink;
Stream get eventStream => _eventData.stream;
String channelName = '';
String prevChannelName = '';
String eventName = '';
PusherController initPusher() {
PusherOptions options = PusherOptions(
cluster: "xxxxxxxxxx",
);
pusher = PusherClient("xxxxxxxxx", options, autoConnect: true, enableLogging: true);
return this;
}
PusherController setChannelName(String name) {
channelName = name;
return this;
//print("channelName: ${channelName}");
}
PusherController setEventName(String name) {
eventName = name;
return this;
//print("eventName: ${eventName}");
}
PusherController subscribePusher() {
channel = pusher.subscribe(channelName);
pusher.onConnectionStateChange((state) {
debugPrint("previousState: ${state!.previousState}, currentState: ${state.currentState}");
});
pusher.onConnectionError((error) {
debugPrint("error: ${error!.message}");
});
//Bind to listen for events called and sent to channel
channel.bind(eventName, (PusherEvent? event) {
debugPrint("xxxxxxxxx From pusher xxxxxxxxx");
_inEventData.add(event!.data);
prevChannelName = eventName;
});
notifyListeners();
return this;
}
PusherController connectPusher() {
pusher.connect();
return this;
}
void disconnectPusher() async {
await channel.unbind(eventName);
await pusher.disconnect();
}
}