首页 > 解决方案 > How to get data from rxjs?

问题描述

I have a file to save the random id to AsyncStorage.

AppService.js

import Rx from 'rxjs/Rx';

import uuid from 'uuid/v4'

import StorageService from '../storage/StorageService'

export default class AppService {
  constructor() {
    this.deviceuuid = null
  }

  rxInit() {
    return StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
      if (deviceuuid == null) {
        this.deviceuuid = uuid()
        console.log('deviceuuid is empty, create one')
        return StorageService.shared.set('deviceuuid', this.deviceuuid)
      } else {
        this.deviceuuid = deviceuuid
        return Rx.Observable.of(this.deviceuuid)
      }
    }).do((deviceuuid) => {
        console.log(`deviceuuid is ${deviceuuid}`)
    })
  }
}

AppService.shared = new AppService()

StorageService.js

import Rx from 'rxjs/Rx'

import { AsyncStorage } from 'react-native'

import Storage from 'react-native-storage'

let storage = new Storage({
  size: 1000,
  storageBackend: AsyncStorage,
  defaultExpires: null,
})  

export default class StorageService {
  set(key, value) {
    return Rx.Observable.fromPromise(storage.save({key: key, data: value})).map(() => value)
  }

  get(key) {
    return Rx.Observable.fromPromise(storage.load({key: key})).catch(() => Rx.Observable.of(null))
  }

  remove(key) {
    return Rx.Observable.fromPromise(storage.remove({key: key})).catch(() => Rx.Observable.of(null))
  }
}

StorageService.shared = new StorageService()

When I build the project I can see deviceuuid is 14c629ee-0dc7-43ef-91c2-eed642271670

Now I want to get the deviceuuid from another screen.

  componentWillMount() {
    console.log('LoginScreen componentWillMount');
    console.log('rxInit data =>', AppService.shared.rxInit())

    let testId = StorageService.shared.get('deviceuuid')
    console.log('testID', testId);

    StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
      console.log('deviceuuid', deviceuuid);
      this.setState({ uuid: deviceuuid })
    }).do((deviceuuid) => {
      console.log(`LoginScreen deviceuuid is ${deviceuuid}`)
    })
  }

the result like the image

enter image description here

I have no idea how to get deviceuuid.

and the code is not working. I can't see any console log result.

StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
  console.log('deviceuuid', deviceuuid);
  this.setState({ uuid: deviceuuid })
}).do((deviceuuid) => {
  console.log(`LoginScreen deviceuuid is ${deviceuuid}`)
})

I'm not familiar with rxjs, any help would be appreciated.

标签: react-nativerxjs

解决方案


推荐阅读