braverhealth / phoenix-socket-dart

Cross-platform and stream-based implementation of Phoenix Sockets
https://pub.dev/packages/phoenix_socket
BSD 3-Clause "New" or "Revised" License
73 stars 37 forks source link

PhoenixChannel using previous user's topic(not a bug need a help!) #47

Closed freewebwithme closed 4 months ago

freewebwithme commented 2 years ago

My scenario is like this. I created 2 users on simulator for testing. When I log in the app, my app will connect socket and add channel with topic like this

 var topic = "cart:$userId";
    var connectedSocket = await _socket!.connect();

    if (connectedSocket!.isConnected &&
        connectedSocket.channels.containsKey(topic) != true) {
      var channel = connectedSocket.addChannel(topic: topic);
      if (channel.state != PhoenixChannelState.joined) {
        var pushResponse = await channel.join().future;

And then when I add a item to cart using this function

  Future<PushResponse>? addToCart(
      {String? productId, int? quantity, int? storeId}) async {
    final Session? session = getIt<Session>();
    print("calling addToCart from CartApi, user_id: ${session!.user!.id}");
    Future<PushResponse>? pushResponse;
    await channel.then(
      (channel) {
        print("Printing current channel info from addToCart function");
        print(channel!.topic);
        print(channel.state.name);
        pushResponse = channel.push(
          "add_to_cart",
          {
            "user_id": session.user!.id,
            "product_id": productId,
            "store_id": storeId,
            "quantity": quantity
          },
        ).future;
      },
    );

    return pushResponse!;
  }

It works but

When I switch to another user (app doesn't restart, just lot out and log in with another user), My channel object is using previous users' channel. I inspect it using print(channel!.topic); It shows me cart:1(previous user) instead of cart:2(current user)

I tried leaving channel when user logs out.

Future<void> leaveChannel() async {
    print("Leaving channel....");
    return await channel.then(
      (channel) {
        print("Leaving from ${channel!.topic}");
        channel.leave();
      },
    );
  }

But it still uses previous channel with topic. I know this problem is from my source code not from this package. but I am stuck on this for couple of days. So Please give me an advice!

vizakenjack commented 1 year ago

Try to use channel.close() and socket.close() and reopen it after relogin