I create a observable using the following code:
我使用以下代码创建一个observable:
let disposeBag = DisposeBag()
let myJust = { (element: String) -> Observable<String> in
return Observable.create { observer in
observer.on(.next(element))
//observer.on(.completed)
return Disposables.create()
}
}
Those code was written in the sample code of RxSwift.
这些代码是在RxSwift的示例代码中编写的。
If I create a empty Observable like myJust. And some time later, how can I send next value to myJust, like:
如果我像myJust一样创建一个空的Observable。一段时间后,我如何向myJust发送下一个值,如:
myJust("????").on(.completed)
But I get the following error:
但是我收到以下错误:
error: value of type 'Observable<String>' has no member 'on'
1 个解决方案
#1
11
You can't. Observable
s can only be observed. If you want to push values, you'll need a Subject
. A Subject
is both an Observable
and an Observer
so it can emit and listen to Events. In RxSwift you can also create a Variable
which you can bind an Observable
to.
你不能。只能观察到可观测量。如果你想推送价值,你需要一个主题。 Subject既是Observable又是Observer,因此它可以发出和监听事件。在RxSwift中,您还可以创建一个可以将Observable绑定到的变量。
Quick example for BehaviorSubject
:
BehaviorSubject的快速示例:
let subject = BehaviorSubject(value: 1)
subject.on(.Next(2))
subject.on(.Next(3))
subject.on(.Completed)
#1
11
You can't. Observable
s can only be observed. If you want to push values, you'll need a Subject
. A Subject
is both an Observable
and an Observer
so it can emit and listen to Events. In RxSwift you can also create a Variable
which you can bind an Observable
to.
你不能。只能观察到可观测量。如果你想推送价值,你需要一个主题。 Subject既是Observable又是Observer,因此它可以发出和监听事件。在RxSwift中,您还可以创建一个可以将Observable绑定到的变量。
Quick example for BehaviorSubject
:
BehaviorSubject的快速示例:
let subject = BehaviorSubject(value: 1)
subject.on(.Next(2))
subject.on(.Next(3))
subject.on(.Completed)