RxSwift如何将两个Observable绑定在一起完成?

时间:2018-08-07 16:53:32

标签: reactive-programming reactivex swift4.1

我有两个Observable,我希望它们在完成任何一个时都以完成事件终止。它们都从相同的序列分支,但是终止条件不同:

{
    "myData": [{
            "data": {
                "product": {
                    "productId": "apple",
                    "productName": "iPhone",
                    "productModel": "6s"
                },
                "statusCode": "active",
                "date": "2018-08-07T00:00:00.000Z"
            },
            "links": [{
                    "productUrl": "test"
                },
                {
                    "productImage": "test"
                }
            ],
            "info": {}
        },
        {
            "data": {
                "product": {
                    "productId": "apple",
                    "productName": "iPhone",
                    "productModel": "7"
                },
                "statusCode": "active",
                "date": "2018-08-07T00:00:00.000Z"
            },
            "links": [{
                    "productUrl": "test"
                },
                {
                    "productImage": "test"
                }
            ],
            "info": {}
        },
        {
            "data": {
                "product": {
                    "productId": "apple",
                    "productName": "Macbook"
                },
                "statusCode": "active",
                "date": "2018-08-07T00:00:00.000Z"
            },
            "links": [{
                    "productUrl": "test"
                },
                {
                    "productImage": "test"
                }
            ],
            "info": {}
        }
    ],
    "metadata": {
        "count": 3,
        "offset": 0
    }
}

如何完成两个可观测对象的组合?

1 个答案:

答案 0 :(得分:1)

我认为您需要手动管理订阅,下面是一个示例:

var disposable1: Disposable?
var disposable2: Disposable?
disposable1 = observable.filter().take(1).subscribe(onDisposed: {
    disposable2?.dispose()
})
disposable2 = observable.distinctUntilChanged().take(2).subscribe(onDisposed: {
    disposable1?.dispose()
})