Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift How to subscribe a observable only one time?

Tags:

swift

rx-swift

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?

like image 596
Bruno Avatar asked Aug 08 '17 03:08

Bruno


People also ask

What is single in RxSwift?

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.

What is subscribe in RxSwift?

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.

What is publish subject in RxSwift?

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.

What is share in RxSwift?

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.


1 Answers

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.

like image 91
Chris Conover Avatar answered Oct 21 '22 16:10

Chris Conover