首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >iOS RxSwift如何从Observable.of(1,2,3)中“拉”?

iOS RxSwift如何从Observable.of(1,2,3)中“拉”?
EN

Stack Overflow用户
提问于 2018-08-13 18:18:41
回答 1查看 179关注 0票数 0

我正在RX快速问题上工作,以模拟4个用户的点击。需求是让它们异步发生,以响应RX中的其他事件。所以我不能用计时器或时刻表。

我正在考虑一个函数,它可以从一个可以观察到的值中“拉”出最多4个值,然后终止。我的问题是:

是什么操作符允许我“拉”或从一开始就完成一个可以观察到的所有元素?

代码语言:javascript
运行
复制
func recursive(duration: int) -> Observable<Int>
{
// logic that may terminate recursion based on network conditions

//logic to terminate if number of taps exceeded
If I take from the taps array observable, and it completes - terminate recursion
}

这样做的目的是在不依赖外部变量的情况下,尝试创建一个“纯”RX实现。我在考虑Zip,但我很难看出它与解决方案的递归性质有什么关系

EN

回答 1

Stack Overflow用户

发布于 2018-08-13 20:03:58

如果我明白你想要什么,几年前我就用承诺做了这样的事情。也许它能帮到你。https://gist.github.com/dtartaglia/2b19e59beaf480535596

下面,我更新了承诺代码以使用Singles:

代码语言:javascript
运行
复制
/**
Repeatedly evaluates a promise producer until a value satisfies the predicate.
`promiseWhile` produces a promise with the supplied `producer` and then waits
for it to resolve. If the resolved value satisfies the predicate then the
returned promise will fulfill. Otherwise, it will produce a new promise. The
method continues to do this until the predicate is satisfied or an error occurs.

- Returns: A promise that is guaranteed to fulfill with a value that satisfies
the predicate, or reject.
*/

func doWhile<T>(pred: @escaping (T) -> Bool, body: @escaping () -> Single<T>, fail: (() -> Single<Void>)? = nil) -> Single<T> {
    return Single.create { event in
        func loop() {
            _ = body().subscribe(onSuccess: { (t) -> Void in
                if !pred(t) {
                    event(SingleEvent.success(t))
                }
                else {
                    if let fail = fail {
                        _ = fail().subscribe(onSuccess: { loop() }, onError: { event(SingleEvent.error($0)) })
                    }
                    else {
                        loop()
                    }
                }
            }, onError: {
                event(SingleEvent.error($0))
            })
        }
        loop()
        return Disposables.create()
    }
}

我不希望你能够仅仅使用上面的内容,但希望你能从中得到灵感。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51828352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档