简体   繁体   English

RxSwift - 订阅行为(观察者:)

[英]RxSwift - behavior of subscribe(observer:)

I'm confused about behavior of subscribe method in RxSwift.我对 RxSwift 中 subscribe 方法的行为感到困惑。
This is sample code.这是示例代码。

let observer1 = PublishSubject<String>()
let observer2 = PublishSubject<String?>()

let observable1 = Observable.just("")
let observable2 = observable1.map { $0 }

_ = observable1.subscribe(observer1) // #1. OK
_ = observable1.subscribe(observer2) // #2. Error
_ = observable2.subscribe(observer2) // #3. Error
_ = observable1.map{ $0 }.subscribe(observer2) // #4. OK

I understand that #2 and #3 get an error.我知道#2 和#3 出现错误。
Because the observer is a nullable-string type, it is strictly different from the type that the observable holds.因为观察者是可空字符串类型,所以它与可观察对象所持有的类型完全不同。

But I can not understand #4.但我无法理解#4。
If directly subscribe of the mapped observable, it did not get an error.如果直接订阅映射的 observable,则不会出错。
As shown in #3, the return value of the mapped observable1 was Observable.如#3所示,映射的observable1的返回值为Observable。

I look forward to reply.我期待着回复。

This is because .map { $0 } actually returns a Observable<String?> in the fourth case!这是因为.map { $0 }在第四种情况下实际上返回一个Observable<String?>

Ww can cast the return value to a Observable<String> : Ww 可以将返回值转换为Observable<String>

_ = (observable1.map{ $0 } as Observable<String>).subscribe(observer2)

It stops working!它停止工作! This implies that the value returned by map without the cast must be different.这意味着没有强制转换的map返回的值必须不同。 And there's only one possibility - Observable<String?> .只有一种可能性 - Observable<String?> $0 can't be implicitly convertible to other types. $0不能隐式转换为其他类型。

The compiler sees that you are calling subscribe(Observable<String?>) and infers the return type of map to be Observable<String?> because only then can subscribe be called successfully.编译器看到您正在调用subscribe(Observable<String?>)并推断map的返回类型为Observable<String?>因为只有这样才能成功调用subscribe

But if you don't give the compiler enough context to figure out the type that map should return, like you did in the let observable2 = ... line, then the compiler thinks you want a Observable<String> .但是如果你没有给编译器足够的上下文来确定map应该返回的类型,就像你在let observable2 = ...行中所做的那样,那么编译器会认为你想要一个Observable<String>

Basically, the compiler is being smart.基本上,编译器很聪明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM