正确使用RxJS获取请求

时间:2015-12-29 13:59:53

标签: react-native rxjs

我正在尝试向我的服务器提取POST请求。我想将它与RxJS一起使用,以更好地概述我的响应数据。现在我可能无法正确使用它......

点按一下按钮后,我在我的Component中调用RxJS fetch:

_btnSendCode: function () {
    var self = this;
    var RelationShipModel = require('../NetworkUtils/RelationShipModel');
    var relationShipType = RelationShipModel(currentIndex);
    var InvitationAction = require('../../../Flux/Actions/InvitationAction');
    InvitationAction.createInvitation(this.state.familyID, relationShipType, this.state.adminSwitch, AuthStore.getUserTokenWithBearer());
    //self.props.navigator.pop();
}

这是我的createInvitation:

var Rx = require('rx');

function notifyMessage(msg:string) {
    if (Platform.OS === 'android') {
        ToastAndroid.show(msg, ToastAndroid.SHORT)
    } else {
        AlertIOS.alert(msg);
    }
}

createInvitation: function (familyID, type, isAdmin, userToken) {
    let source = Rx.Observable.create(function (observer) {
        fetch(API_URL + 'families/' + familyID + '/invitations', {
            method: 'POST',
            headers: {'Authorization': userToken, 'Content-Type': 'application/json'},
            body: JSON.stringify({
                'type': type,
                'isAdmin': isAdmin
            })
        }).then(res => res.json())
            .then(j => {
                observer.onNext(j);
                observer.onCompleted();
            }).catch(observer.onError);
    }).flatMap(function (array) {
        return Rx.Observable.from(array);
    });

    let subscription = source.subscribe(
        function (x) {
            console.log('onNext: %s', x);
            //Dispatcher.dispatch({
            //    actionType: ActionTypes.CREATE_INVITATION,
            //    data: JSON.parse(response._bodyText)
            //});
        },
        function (e) {
            console.log('onError: %s', e);
            notifyMessage(e.message);
        },
        function () {
            console.log('onCompleted');
        }
    );

    console.log(subscription);

所以问题是,onNext,onError或onCompleted永远不会被激活。可能是什么问题呢?我的获取响应应该是正确的。但即使它不正确,我不应该在我的onError中得到错误信息吗?

1 个答案:

答案 0 :(得分:1)

如果observer.onError触发异常,您的代码可能会在不触发JSON.stringify的情况下中断,例如尝试序列化具有循环数据结构的对象。

不是说这是实际问题,让我们试着将你的问题分解成更小的可测试块,所以至少我们会知道哪个部分一直在失败以及为什么会这样。

另外,我建议将代码拆分为较小的observable,以使错误处理更容易:

const body$ = Observable.create( obs => {
    try {
        const body = JSON.stringify({type: ..., isAdmin: ...})
        obs.onNext(body)
        obs.onCompleted()
    } catch (err) {
        obs.onError(err)
    }

})
const request$ = body$.flatMap(
                        body => Observable.of( fetch(..., {body, ...}))
                    )
                    .do(...) // start with this if still having issues
                    .catch(...) // you should be able to drop this one later

const source$ = request$.flatMap(
   res => Observable.of(res.json())
).catch(...)

source$.subscribe(...)

无法运行此代码atm,但希望一般的要点是明确的 - 通常,为了拥有更小的,可测试的可观察量,这是值得的。