将 Observable 分配给另一个
Assigning Observable to another
我有这个对象TryOut
,初始化时,它每隔2 seconds
执行一个私有方法。在该方法 func execute() 中,有一个 internalStream
类型的局部变量 Observable<Int>
用于捕获我希望向外界发送的数据。
The issue is that even though internalStream
is assigning to a member property public var outsideStream: Observable<Int>?
, There aren't any events coming from subscribing to outsideStream
. Why though ? is there any reason behind that ?
工作案例
唯一可行的方法是将闭包作为成员 属性 public var broadcast:((Observable<Int>) -> ())? = nil
,然后通过 broadcast?(internalStream)
[=] 在 execute
方法中引发它22=]
在此 gist 中可以找到示例代码。谢谢您的帮助。
对于这种情况,当你想自己生产事件时,最好使用RxSwift
提供的*Subject
中的任何一个。
例如:
将 outputStream
声明更改为:
public var outsideStream = PublishSubject<Int>()
以正确的方式产生事件:
@objc private func execute() {
currentIndex += 1
if currentIndex < data.count {
outsideStream.onNext(data[currentIndex])
}
guard currentIndex + 1 > data.count && timer.isValid else { return }
outsideStream.onCompleted()
timer.invalidate()
}
以及用法:
let participant = TryOut()
participant.outsideStream
.subscribe(
onNext: { print("income index:", [=12=]) },
onCompleted: { print("stream completed") }
)
.disposed(by: bag)
给你输出:
income index: 1
income index: 2
income index: 3
income index: 4
income index: 5
stream completed
P.S。此外,还有另一种方法可以通过 RxSwiftExt
库使用(或复制)retry
方法来实现。
我有这个对象TryOut
,初始化时,它每隔2 seconds
执行一个私有方法。在该方法 func execute() 中,有一个 internalStream
类型的局部变量 Observable<Int>
用于捕获我希望向外界发送的数据。
The issue is that even though
internalStream
is assigning to a member propertypublic var outsideStream: Observable<Int>?
, There aren't any events coming from subscribing tooutsideStream
. Why though ? is there any reason behind that ?
工作案例
唯一可行的方法是将闭包作为成员 属性 public var broadcast:((Observable<Int>) -> ())? = nil
,然后通过 broadcast?(internalStream)
[=] 在 execute
方法中引发它22=]
在此 gist 中可以找到示例代码。谢谢您的帮助。
对于这种情况,当你想自己生产事件时,最好使用RxSwift
提供的*Subject
中的任何一个。
例如:
将 outputStream
声明更改为:
public var outsideStream = PublishSubject<Int>()
以正确的方式产生事件:
@objc private func execute() {
currentIndex += 1
if currentIndex < data.count {
outsideStream.onNext(data[currentIndex])
}
guard currentIndex + 1 > data.count && timer.isValid else { return }
outsideStream.onCompleted()
timer.invalidate()
}
以及用法:
let participant = TryOut()
participant.outsideStream
.subscribe(
onNext: { print("income index:", [=12=]) },
onCompleted: { print("stream completed") }
)
.disposed(by: bag)
给你输出:
income index: 1
income index: 2
income index: 3
income index: 4
income index: 5
stream completed
P.S。此外,还有另一种方法可以通过 RxSwiftExt
库使用(或复制)retry
方法来实现。