Group Group Group Group Group Group Group Group Group

How, when and why to use asObservable() (Chapter 4)

There is a code like this in chapter 4:

.subscribe(onNext: { [weak self] photos in
self?.updateUI(photos: photos)
.disposed(by: bag)

Images is BehaviorRelay.

And no one explains to us how to use asObservable(), why we need it and what it is in general.

And I haven’t found any explanations on the Internet.

Maybe someone will explain us once and for all?


I have the same question and it seems no one’s ever answered this, so commenting for a better reach.

@stsoslan Thanks very much for your question!

From what I found, It’s a protocol conformance for ObservableConvertibleType. To get a better understanding, look at the ObservableType protocol and what objects conform to it (namely things like subjects, etc.). The only guarantee is that the object will return an Observable in response to a call to asObservable. This guarantee allows you to use all types that can provide an Observable together in the same operator chain.

I’m not sure if that helps, but I hope it does :slight_smile:

In essence this is similar to Strings conformance to CustomStringConvertible.

Still don’t understand.

CustomStringConvertible gives us a property to see textual description. AsObservable is not a property, it’s a method.

We can subscribe to images without “asObservable”.

Maybe asObservable like changing type of object? Like:
var a = 1
bar b = String(a)

And I have the same question too…

The same pattern is repeated in Chapter 10: categories.asObservable(), events.asObservable() where both categories & events are BehaviorRelay.

The question was asked at least twice:

with no definitive answer.

The only insight was given by @jecht83

seems that the intention to use it is to make clear to the user that only changes in self.images are being observed and nothing else

Somebody could verify/confirm aboves?
That it is only about “making intention clear”.

This topic was automatically closed after 166 days. New replies are no longer allowed.