Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observables vs Tasks - preferred implementation?

I simply want to retrieve data asynchronously, and after retrieving the data, show it in the UI (Winforms).

Using .net 4.0, there are 2 ways that I can implement this (I know there are more, but I am using these two):

    var task = Task.Factory.StartNew(() => RetrieveData());
    task.ContinueWith(x => SetDataInUi(x.Result), TaskScheduler.FromCurrentSynchronizationContext());

OR

var obs = Observable.Start(() => RetrieveData());
obs.ObserveOn(SynchronizationContext.Current).Subscribe(x => SetDataInUi(x));

To the best of my understanding, these will both do the same thing. Is there a reason to choose one over the other?

like image 214
user981225 Avatar asked Feb 09 '12 18:02

user981225


People also ask

Is Promises are more advanced than observables?

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.

Are observables and promises cancellable?

Observable subscriptions are cancellable; promises aren't Once you start a promise, you can't cancel it. The callback passed to the Promise constructor will be responsible for resolving or rejecting the promise.

Is observable lazy?

No, they aren't lazy, but they are asynchronous.

What are observables in JavaScript?

Observable JavaScript represents a progressive way of handling events, async the activity, and multiple values in JavaScript. These observables are just the functions that throw values and Objects known as observers subscribe to such values that define the callback functions such as error(), next() and complete().


1 Answers

If you just want to request data from somewhere and print it to screen, I would prefer the first solution.

The second one works too, but RX was designed to help you with data flows. And we all agree it's not cool to use a complex solution when you can use a simple one :)

like image 188
Rodrigo Vedovato Avatar answered Nov 15 '22 08:11

Rodrigo Vedovato