слушатели pubnub не работают в реакции-родной - PullRequest
1 голос
/ 10 апреля 2020

Я работаю над приложением для отслеживания геолокации в режиме реального времени, используя pubnub и response-native-maps в Reaction-native. pubnub.publish() работает при вызове внутри Geolocation.getCurrentLocation() и Geolocation.watchPosition() внутри componentDidMount().

Вот код, который работает нормально:

      Geolocation.getCurrentPosition(
        position => {
          if (this.state.allowsGPS) {
            this.pubnub.publish({
              message: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                from: '1'
              },
              channel: "location_tracker_channel"
            }, () => console.log("publish 1"))
            let users = this.state.users;
            let tempUser = {
              uuid: this.pubnub.getUUID(),
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            }
            users.set(tempUser.uuid, tempUser)
            this.setState({
              users,
              currentLocation: position.coords
            })
          }
        },
        error => console.log("error in currentPos:", error),
        {
          enableHighAccuracy: true,
          distanceFilter: 0.1
        }
      )

      Geolocation.watchPosition(
        position => {
          this.setState({
            currentLocation: position.coords
          })
          if (this.state.allowsGPS) {
            console.log("published:", position.coords)
            this.pubnub.publish({
              message: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                from: '2'
              },
              channel: "location-tracker-channel"
            }, () => console.log("publish 2"))
          }
        },
        err => console.log("err in geolocation:", err),
        {
          enableHighAccuracy: true,
          distanceFilter: 0.1
        }
      )
    } else {
      console.log("location permission denied")
    }
  }

Но он не работает в componentDidUpdate(), который должен публиковать sh {hideUser:true}, когда this.state.allowsGPS равно true и публикует sh информацию о пользователях, когда false. Хотя в журналах он печатает publish 4 и publish 3 соответственно, но не слушает никаких таких сообщений.

Вот код, который не работает:

 componentDidUpdate(prevProps, prevState) {
    if (prevState.allowsGPS != this.state.allowsGPS) {
      if (this.state.allowsGPS) {
        let users = this.state.users;
        let tempUser = {
          uuid: this.pubnub.getUUID(),
          latitude: this.state.currentLocation.latitude,
          longitude: this.state.currentLocation.longitude,
          image: this.state.currentPicture,
          username: this.state.username,
          from: '3'
        }
        users.set(tempUser.uuid, tempUser);
        this.pubnub.publish({
          message: tempUser,
          channel: "location_tracker_channel",
        }, () => console.log("publish 3"))
        this.setState({
          users
        })
      }
      else {
        let users = this.state.users;
        let uuid = this.pubnub.getUUID();

        users.delete(uuid);
        let tempMssg = { hideUser: true, from: '4' }
        this.pubnub.publish({
          message: tempMssg,
          channel: "location_tracker_channel",
        }, () => console.log("publish 4"))

        this.setState({
          users
        })
      }
    }
  }

Вот мой полный код:

async componentDidMount() {
    this.setUpApp();
  }

  async setUpApp() {
    this.pubnub.addListener({
      message: mssg => {
        let users = this.state.users;
        if (mssg.message.hideUser) {
          users.delete(mssg.publisher);
          this.setState({
            users
          })
        } else {
          let oldUser = this.state.users.get(mssg.publisher);
          let newUser = {
            uuid: mssg.publisher,
            latitude: mssg.message.latitude,
            longitude: mssg.message.longitude
          }
          if (mssg.message.message) {
            setTimeout(mssg.publisher, this.clearMessage, 5000, mssg.publisher);
            newUser.message = mssg.message.message
          } else if (oldUser) {
            newUser.message = oldUser.message
          }
          users.set(newUser.uuid, newUser);
          this.setState({
            users
          })
        }
      }
    })
    this.pubnub.subscribe({
      channels: ["location-tracker-channel"],
      withPresence: true
    })

    let granted;
    if (Platform.OS == "android") {
      granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Location Permissions',
          message: 'LocationTracker needs to access your location',
          buttonNegative: 'NO',
          buttonPositive: 'YES'
        }
      )
    }
    if (granted == PermissionsAndroid.RESULTS.GRANTED || Platform.OS == 'ios') {
      Geolocation.getCurrentPosition(
        position => {
          if (this.state.allowsGPS) {
            this.pubnub.publish({
              message: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                from: '2'
              },
              channel: "location_tracker_channel"
            }, () => console.log("publish 1"))
            let users = this.state.users;
            let tempUser = {
              uuid: this.pubnub.getUUID(),
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            }
            users.set(tempUser.uuid, tempUser)
            this.setState({
              users,
              currentLocation: position.coords
            })
          }
        },
        error => console.log("error in currentPos:", error),
        {
          enableHighAccuracy: true,
          distanceFilter: 0.1
        }
      )

      Geolocation.watchPosition(
        position => {
          this.setState({
            currentLocation: position.coords
          })
          if (this.state.allowsGPS) {
            console.log("published:", position.coords)
            this.pubnub.publish({
              message: {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                from: '2'
              },
              channel: "location-tracker-channel"
            }, () => console.log("publish 2"))
          }
        },
        err => console.log("err in geolocation:", err),
        {
          enableHighAccuracy: true,
          distanceFilter: 0.1
        }
      )
    } else {
      console.log("location permission denied")
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.allowsGPS != this.state.allowsGPS) {
      if (this.state.allowsGPS) {
        let users = this.state.users;
        let tempUser = {
          uuid: this.pubnub.getUUID(),
          latitude: this.state.currentLocation.latitude,
          longitude: this.state.currentLocation.longitude,
          image: this.state.currentPicture,
          username: this.state.username,
          from: '3'
        }
        users.set(tempUser.uuid, tempUser);
        this.pubnub.publish({
          message: tempUser,
          channel: "location_tracker_channel",
        }, () => console.log("publish 3"))
        this.setState({
          users
        })
      }
      else {
        let users = this.state.users;
        let uuid = this.pubnub.getUUID();

        users.delete(uuid);
        let tempMssg = { hideUser: true, from: '4' }
        this.pubnub.publish({
          message: tempMssg,
          channel: "location_tracker_channel",
        }, () => console.log("publish 4"))

        this.setState({
          users
        })
      }
    }
  }

Используемые библиотеки: * версия pubnub-4.27.4 * реакция-нативная версия -0.62.1 '* реакция-нативная-карта версий =' 0.27.1 '

...