我如何在没有嵌套订阅的情况下订阅命令执行信号的完成? [英] How can I subscribe to the completion of a command's execution signals without a nested subscription?

查看:102
本文介绍了我如何在没有嵌套订阅的情况下订阅命令执行信号的完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下操作,但没有成功.使用-subscribeNext:的等效项可以正常工作.

I tried the following without success. The equivalent using -subscribeNext: works as expected.

// A
[[_viewModel.loginCommand.executionSignals flatten] subscribeCompleted:^{
    NSLog(@"A");
}];

我唯一可行的实现如下:

My only working implementation is as follows:

// B
[_viewModel.loginCommand.executionSignals subscribeNext:^(RACSignal *loginSignal) {
    [loginSignal subscribeCompleted:^{
        NSLog(@"B");
    }];
}];

为什么-flatten在"A"中不起作用,如何重写"B"以不使用嵌套订阅?

Why doesn't -flatten work in "A", and how I can I rewrite "B" to not use a nested subscription?

推荐答案

-flatten运算符返回仅在所有内部信号都已完成时才完成的信号,这也需要外部信号也要完成. -concat也是如此.因此,一旦您应用了任何一个运算符,结果信号就不会表示单个完成,而只能表示最终的汇总完成.

The -flatten operator returns a signal that completes only when all of the inner signals have completed, which requires the outer signal to complete as well. The same is true of -concat. Because of this, once you apply either operator, the resulting signal has no representation of individual completion, only the final aggregate completion.

作为嵌套订阅的替代,您可以转换内部信号,以便它们发送表示完成的值.一种方法是使用-materialize:

Alternative to nested subscriptions, you could transform the inner signals so that they send a value that signifies completion. One way of doing this is with -materialize:

[[[_viewModel.loginCommand.executionSignals
    map:^(RACSignal *loginSignal) {
        // Using -ignoreValues ensures only the completion event is sent.
        return [[loginSignal ignoreValues] materialize];
    }]
    concat]
    subscribeNext:^(RACEvent *event) {
        NSLog(@"Completed: %@", event);
    }];

请注意,我使用了-concat而不是-flatten,因为它与RACCommand的默认串行执行的语义相匹配.在这种情况下,它们最终会执行相同的操作,因为命令一次只执行一个信号,所以-flatten会退化为-concat的行为.

Note that I used -concat instead of -flatten, since it matches the semantics of RACCommand's default serial execution. They ultimately do the same in this case, -flatten degenerates to the behavior of -concat because the command only executes signals one at a time.

使用-materialize并不是唯一的方法,它只是发送一个表示完成的值,但这可能是您认为对用例有意义的任何值.

Using -materialize isn't the only way to do this, it just happens to send a value that represents completion, but that could be any value that you find appropriately significant for your use case.

这篇关于我如何在没有嵌套订阅的情况下订阅命令执行信号的完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆