如何从rxjs获取数据?

时间:2019-05-10 08:57:00

标签: react-native rxjs

我有一个文件将随机ID保存到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()

构建项目时,我可以看到deviceuuid is 14c629ee-0dc7-43ef-91c2-eed642271670

现在我想从另一个屏幕上获取deviceuuid

  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}`)
    })
  }

像图片一样的结果

enter image description here

我不知道如何获得deviceuuid

并且代码不起作用。我看不到任何控制台日志结果。

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

我对rxjs不熟悉,将不胜感激。

0 个答案:

没有答案