I want to subscribe to an observable, but in some logic, I will re-subscribe to it. If I don't want to write some special logic for it, how can I dispose the last subscription when I add a new one? Or, when I subscribe to it, how can I know if this observable has been subscribed to already?
A Single is something like an Observable that instead of emitting a series of values, is guaranteed to be return either a value or an error. Emits exactly one element, or an error. Doesn't share side effects.
The Subscribe is how you connect an observer to an Observable. onNext This method is called whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable. When a value is added to an observable it will send the next event to its subscribers.
There are four subject types in RxSwift: PublishSubject : Starts empty and only emits new elements to subscribers. BehaviorSubject : Starts with an initial value and replays it or the latest element to new subscribers.
In (very) simple terms, share passes a ReplaySubject to multicast. Internally, the subject is subscribed to the source observable (the underlying subscription) and its emitted values are handed to the subject, which in turn passes the values to the actual subscribers.
The simplest solution for what you are looking for is indeed the method that they provided for just that - func take(_ count: Int)
.
Here is a playground sample:
import RxSwift
var variable = Variable(1)
variable.asObservable().take(1).subscribe(
onNext: { print("onNext: \($0)") },
onError: { print("onError: \($0)") },
onCompleted: { print("onCompleted") },
onDisposed: { print("onDisposed") })
variable.value = 2
print("done")
The results are:
onNext: 1
onCompleted
onDisposed
done
And yes, this is useful in places where you want to filter an event through a stream, in a location where it is awkward to store a subscription.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With