如果未发出某个值,则在n秒后超时

时间:2019-04-03 09:30:27

标签: rxjs angular6 observable angularfire2

我正在使用angularfire2将状态为NEW的对象推入Firebase。我的后端正在侦听该列表上的写入内容,并将针对状态为NEW的每个新请求执行操作。 我想处理3种可能的结果:成功,错误和超时。

class VC: UIViewController, UICollectionViewDelegate {

    // first arg - section, second - selected indexes
    typealias DataSource = [Int: [IndexPath]]
    var selectedRows: DataSource = [:]


    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        cell.isSelected = selectedRows[indexPath.section]?.contains(indexPath) ?? false
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let contains = selectedRows[indexPath.section]?.contains(indexPath) ?? false
        if contains {
            var current = selectedRows[indexPath.section]
            current.removeAll { $0 == indexPath }
            selectedRows[indexPath.section] = current
        } else {
            selectedRows[indexPath.section] = (selectedRows[indexPath.section] ?? []) + [indexPath]
        }
        collectionView.cellForItem(at: indexPath).isSelected = !contains
    }
}

无论我收到错误还是成功,都会发生超时。仅在60秒后仍未收到超时怎么办?

1 个答案:

答案 0 :(得分:0)

我以这种方式重写了它,它正在起作用:

add(book: Book) {
        return this.authentication.user.pipe(
            take(1),
            mergeMap(user => {
                // Set owner for the backend to handle correctly
                book.setOwner(user.uid);

                // Add book request
                const queueRef = this._afqueue.list(this.ADD_BOOK_QUEUE_PATH);
                const pushPromise = queueRef.push({ status: { code: 'NEW' }, ...book })
                    .then(ref => {
                        console.log('Request to add a new book added to queue.');
                        return ref;
                    }) as Promise<any>;
                return from(pushPromise);
            }),
            mergeMap(ref => {
                return this._afqueue.object(this.ADD_BOOK_QUEUE_PATH + '/' + ref.key)
                    .valueChanges();
            }),
            map(snap => snap['status']),
            filter(status => (status['code'] === 'SUCCESS' || status['code'] === 'ERROR')),
            first(),
            timeout(60000), // timeout after 60 secondes
            mergeMap(status => {
                console.log(status);
                console.log(status['code'])
                if (status['code'] === 'SUCCESS') {
                    return of(status['book_id']);
                    //return status['book_id'];
                }
                else if (status['code'] === 'ERROR') {
                    throwError(status['error']);
                }
            })
        );
    }