On RxCocoa I was wondering why the PublishRelay doesn't have an asDriver() method like the BehaviorRelay ? Currently if I want to convert the publishRelay into a Driver, I have to specify what to return in case of error which seems weird given that the relays can't generate errors...
Those two versions of ...Relay are used to model different concepts:
BehaviorRelay represents State
PublishRelay represents Events
It makes sense to replay State, hence BehaviorRelay replays its latest value.
It makes less (no?) sense to replay Events, hence PublishRelay does not replay its latest value.
With this in mind, it makes sens for a BehaviorRelay to be transformable to Driver, as a driver drives the application using State. The sharing strategy for BehaviorRelay and Driver is to share side effects and replay the latest value while at least one observable is connected.
A PublishRelay is better represented by a Signal, so you probably could use a Signal to emit to. The sharing strategy in this case is will not replay the latest value, but still share the side effects while at least one observable is connected.
(I build this answer using this great comment from #freak4pc on RxSwift's repository)
If someone need a simple example:
publishRelay
.asDriver(onErrorDriveWith: Driver.empty())
.drive(onNext: { value in
})
.disposed(by: disposeBag)
Related
I have an interesting query with regard to #MainActor and strict concurrency checking (-Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks)
I have functions (Eg, Analytics) that at the lowest level require access to the device screen scale UIScreen.main.scale which is isolated to MainActor. However I would prefer not to have to declare the entire stack of functions above the one that accesses scale as requiring MainActor.
Is there a way to do this, or do I have no other options?
How would be the best way to ensure my code only ever calls UIScreen once and keeps the result available for next time without manually defining a var and checking if its nil? Ie is there a kind of computed property that will do this?
Edit: Is there an equivalent of this using MainActor (MainActor.run doesn't do the same thing; it seems to block synchronously):
DispatchQueue.main.async {
Thanks,
Chris
Non-UI code should not rely directly on UIScreen. The scale (for example), should be passed as a parameter, or to actors in their init. If the scale changes (which it can, when screens are added or removed), then the new value should be sent to the actor. Or the actor can observe something that publishes the scale when it changes.
The key point is accessing UIScreen from a random thread is not valid for a reason. The scale can in fact change at any time. Reading it from an actor is and should be an async call.
It sounds like you have some kind of Analytics actor. The simplest implementation of this would be to just pass the scale when you create it.
I make an app using firestore and a bottom navigation bar in Flutter. The problem is that when I switch between tabs, the build method is called everytime. The build method downloads data from firestore. Therefore, the app flickers when I switch tabs (the spinning bar is showed for a very short time). I tried to fix this by moving the firestore stream to the constructor. However, since the stream can emit before the build method, it loads forever.
A solution could been to save the last value that was emitted. I tried to fix this using the shareReplay method in Rx, but they have not implemented in RxDart yet. So, what is the best practice to implement this?
Use the shareValue operator of rxdart:
final observable = Observable(yourStream).shareValue();
Internally, this operator uses a BehaviorSubject. It will subscribe to the stream as soon as there is a single subscriber (it will only subscribe once), and unsubscribe (and dispose the subject) when there are no more subscribers.
Also, as you said, you have to create the observable in initState or a similar method (NOT the build method!). The observable should be stored in a field in the State.
In the currently accepted answer, the Observable class in RXDart has now been deprecated. Instead, you could use a BehaviorSubject but its probably best to use a ValueConnectableStream instead, like this:
final newStream = ValueConnectableStream(yourStream).autoConnect()
See the RXDart docs for more info.
Convert stream to BehaviorSubject in rxDart.
BehaviorSubject<Data> _subject = BehaviorSubject<Data>();
stream.listen((x) => _subject.add(x));
I ran the flutter app in release mode and the lag was gone, without any modifications.
You could have a look at BehaviorSubject in rxdart. According to the docs
The latest item that has been added to the subject will be sent to any new listeners of the subject.
I've created some very basic data bindings with variables between my VC and VM using RxSwift (which I've very new to), and am now perplexed as to how best communicate other UI actions from the VM that need additional data passed along with them.
Such as trigger popup alerts for error message passing, navigation controls, etc. as I want to send parameters along with them.
I've thought about using delegation again. But would it be inappropriate to mix bindings and delegation together in the same VM?
I'd like to abstract a pattern that can template to other MVVM areas of the app that would need to do the same thing for each VC/VM mix.
This can easily turn into an opinion based question, but if you want to stick with RxSwift, and I assume you do, the best way is to create subscriptions from the VC to VM. In essence, your VM would subscribe to a Variable, PublishSubject or similar in the VC and you would handle those where necessary.
For example of something like this using Strings as data:
let subject = PublishSubject<String>()
// As you can see the subject casts nicely, because it's an Observable subclass
let observable : Observable<String> = subject
observable
.subscribe(onNext: { text in
print(text)
})
.addDisposableTo(disposeBag)
// You can call onNext any time you want to emit a new item in the sequence
subject.onNext("Hey!")
subject.onNext("I'm back!")
You can have a look at more examples here:
http://swiftpearls.com/RxSwift-for-dummies-3-Subjects.html
What are the differences between observable and subject.
When I define a observable type variable. It can emit onNext,onComplete,onDispose. However subject can do the same. When should I use observable and in what case should I use subject?
In order to understand the difference between them, we should mention that Observable is:
In ReactiveX an observer subscribes to an Observable. Then that
observer reacts to whatever item or sequence of items the Observable
emits. This pattern facilitates concurrent operations because it does
not need to block while waiting for the Observable to emit objects,
but instead it creates a sentry in the form of an observer that stands
ready to react appropriately at whatever future time the Observable
does so.
In other words, observable is data producer (responsible for posting notifications to be observed).
Actually, Subject is a special type of Observables (you still can subscribe to messages like any other observable):
A Subject is a sort of bridge or proxy that is available in some
implementations of ReactiveX that acts both as an observer and as an
Observable. Because it is an observer, it can subscribe to one or more
Observables, and because it is an Observable, it can pass through the
items it observes by reemitting them, and it can also emit new items.
but the thing is subject is a representation -as mentioned in the documentation- of both observable and observer, which means that subject might be data producer (responsible for posting notifications to be observed or data consumer (responsible for receiving notifications).
Also: For checking the types of the subjects, you might want to check: RxSwift Subject Types.
I think and as per I learned about this both topics, i can say that,
Observables
An Observable(fundamental part of Rx) is sequence with some special features. and most important feature is asynchronous. Observables produce some events(i.e onNext, onError, onCompleted), which called as emitting. Events contains some value(i.e Int, Bool, Array or custom type).
Subjects
Simple observable can only emits events, which can be subscribed. but what if we want to add some value on current observable(also called self observer). So simply i can say that something that works as an observable and also as a observer is called subjects.
You got a couple of answers explaining the difference between Observables and Subjects, but nobody has covered your second question...
When should I use observable and in what case should I use subject?
Here is an excellent, if complex, answer to that question:
http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx
The TL;DR is this. Use an Observable whenever possible, use a Subject whenever necessary.
You use a Subject whenever you need a hot observable and don't already have an observable to work with. RxCocoa, for example, uses Subjects extensively to create observables for you that are tied to particular UI elements. They are primarlly for bridging non-Rx code into Rx code and connecting producers to consumers where the latter must be created first for some reason.
If I write the following Dart code, how do I know which click handler happens first?
main() {
var button = new ButtonElement();
var stream = button.onClick.asBroadcastStream();
stream.listen(clickHandler1);
stream.listen(clickHandler2);
}
Let's say I'm in other code that doesn't know anything about the first two click handlers, but I register another one.
Can I know that the stream has two listeners?
Can I pause or cancel all other subscribers?
If I write button.onClick.asBroadcastStream() again elsewhere, does it point to the same stream as was used in main?
Can I say in one of the handlers to not pass event on to the other broadcast listener? Is that a consumer?
Let's say I'm in other code that doesn't know anything about the first
two click handlers, but I register another one.
Can I know that the stream has two listeners?
No, you can't. You could extend the stream class or wrap it and provide this functionality yourself, but it does not feel like a good design choice, because I don't think a listener should know about other listeners. What are you trying to do exactly? Perhaps there's a better way than letting listeners know about each other.
Can I pause or cancel all other subscribers?
You can cancel/pause/resume only the subscriber you are dealing with. Again, you probably shouldn't touch other listeners, but I guess you could wrap/extend the Stream class to have this behavior.
If I write button.onClick.asBroadcastStream() again elsewhere, does it point to the same stream as was used in main?
No, at least not at the current version of SDK. So, unfortunately, you need to store a reference to this broadcast stream somewhere, and refer to it, because calling asBroadcastStream() multiple times will not yield in the result you might expect. (Note: at least based on quick testing: http://d.pr/i/Ip0K although the documentation seems to indicate different, I have yet to test a bit more when I find the time).
Can I say in one of the handlers to not pass event on to the other broadcast listener?
Well, there's stopPropagation() in the HTML land which means that the event won't propagate to other elements, but it's probably not what you were looking for.
For being able to stop an event firing in other listeners, there needs to be an order of which the listeners are getting called. I believe the order is the order of registration of those listeners. From the design perspective, I don't think it would be a good idea to allow a listener to cancel/pause others.
Event propagation in HTML makes sense since it's about hierarchy, but here we don't have that (and even in case of events in HTML there can be multiple listeners for the single element).
There's no way to assign weight to listeners or define the order of importance, therefore it's not surprising that there isn't a way to stop the event.
Instead of letting listeners know about each other and manipulate each other, maybe you should try to think of another way to approach your problem (whatever that is).
Is that a consumer?
The StreamConsumer is just a class that you can implement if you want to allow other streams to be piped into your class.
Can I know that the stream has two listeners?
No, you have a ´Stream´ that wraps the DOM event handling. There is no such functionality.
Can I pause or cancel all other subscribers?
Look at Event.stopPropagation() and Event.stopImmediatePropagation(), and possibly Event.preventDefault().
If I write button.onClick.asBroadcastStream() again elsewhere, does it point to the same stream as was used in main?
[Updated] No, the current implementation doesn't gives you the same Stream back since the onClick getter returns a new stream every time it is invoked. However, the returned stream is already a broadcast stream so you shouldn't invoke asBroadcastStream() on it. If you do you will hower just get a reference to the same object back.
Stream<T> asBroadcastStream() => this;
Can I say in one of the handlers to not pass event on to the other broadcast listener? Is that a consumer?
Again, take a look at Event.stopPropagation() and Event.stopImmediatePropagation(), and possibly Event.preventDefault().