ReactiveUI: unable to run code in background thread

Just chatting with RxUI and trying to find a useful example ...

I have a WPF view with a ListBox and a button. When I click the (Go) button, I want to run the method in the background thread, and the results that it creates will be added to the ListBox. I am logging a thread id to check what is running where. The problem is that I always see all the operations occurring in one thread. I tried pointing Scheduler.Default to CreateAsyncObservable, but then nothing is added to the ListBox.

public class MainViewModel : ReactiveObject
{
    public MainViewModel()
    {
        Results = new ReactiveList<string>();

        var seq = ReactiveCommand.CreateAsyncObservable(_ => GetAsyncResults());

        seq.ObserveOn(Scheduler.CurrentThread);

        seq.Subscribe(s =>
        {
            Results.Add(string.Format("{0} thread {1}", s, Thread.CurrentThread.ManagedThreadId));
        });

        Results.Add(string.Format("main thread {0}", Thread.CurrentThread.ManagedThreadId));

        Go = ReactiveCommand.Create();
        Go.Subscribe(_ => seq.Execute(null));
    }

    public static IObservable<string> GetAsyncResults()
    {
        Thread.Sleep(1000);
        return (new[] {"Rod", "Jane", "Freddy"}).ToObservable();
    }

    private readonly ObservableAsPropertyHelper<List<string>> _strings;
    public List<string> Strings {get { return _strings.Value; }}

    public ReactiveCommand<object> Go { get; protected set; }

    public ReactiveList<string> Results { get; set; }
}
+2
source share
1 answer

Rx , , GetAsyncResults . RxApp.TaskpoolScheduler, .

public static IObservable<string> GetAsyncResults()
{
    return (new[] {"Rod", "Jane", "Freddy"}).ToObservable(RxApp.TaskpoolScheduler);
}

seq.ObserveOn(Scheduler.CurrentThread);

,

Go = ReactiveCommand.Create();

?

+1

All Articles