Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8320579
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T22:41:51+00:00 2026-06-08T22:41:51+00:00

I’m currently working on Windows Phone applications and I would like to use Reactive

  • 0

I’m currently working on Windows Phone applications and I would like to use Reactive Extensions to create asynchronism to have a better UI experience.

I use the MVVM pattern: my View has a ListBox binded in my ViewModel to an ObservableCollection of Items. An Item has traditional properties like Name or IsSelected.

<ListBox SelectionMode="Multiple" ItemsSource="{Binding Checklist, Mode=TwoWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I instantiate my MainViewModel in App.xaml.cs:

public partial class App : Application
{
    private static MainViewModel _viewModel = null;

    public static MainViewModel ViewModel
    {
        get
        {
            if (_viewModel == null)
                _viewModel = new MainViewModel();

            return _viewModel;
        }
    }

    [...]
}

And I load my data in MainPage_Loaded.

public partial class MainPage : PhoneApplicationPage
{
   public MainPage()
    {
        InitializeComponent();
        this.DataContext = App.ViewModel;
        this.Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
    }

    private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        App.ViewModel.LoadData();
    }
}

I load my data from my ViewModel (I’m going to move that code to the Model later):

public class MainViewModel : ViewModelBase
{
    public ObservableCollection<Item> _checklist;

    public ObservableCollection<Item> Checklist
    {
        get
        {
            return this._checklist;
        }
        set
        {
            if (this._checklist != value)
            {
                this._checklist = value;
            }
        }
    }

    private const string _connectionString = @"isostore:/ItemDB.sdf";

    public void LoadData()
    {
        using (ItemDataContext context = new ItemDataContext(_connectionString))
        {
            if (!context.DatabaseExists())
            {
                // Create database if it doesn't exist
                context.CreateDatabase();
            }

            if (context.Items.Count() == 0)
            {
                [Read my data in a XML file for example]

                // Save changes to the database
                context.SubmitChanges();
            }

            var contextItems = from i in context.Items
                                select i;

            foreach (Item it in contextItems)
            {
                this.Checklist.Add(it);
            }
        }
    }

    [...]
}

And it works fine, items are updated in the View.

Now I want to create asynchronism. With a traditional BeginInvoke in a new method that I call from the View instead of LoadData it works fine.

public partial class MainPage : PhoneApplicationPage
{
    [...]

    private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        App.ViewModel.GetData();
    }
}

I use a property that I called CurrentDispatcher, it is filled in the App.xaml.cs with App.Current.RootVisual.Dispatcher.

public class MainViewModel : ViewModelBase
{
    [...]

    public Dispatcher CurrentDispatcher { get; set; }

    public void GetData()
    {
        this.CurrentDispatcher.BeginInvoke(new Action(LoadData));
    }

    [...]
}

But I would like to use Reactive Extentions. So I tried different elements of Rx like ToAsync or ToObservable for example but I had some “UnauthorizedAccessException was unhandled” with “Invalid cross-thread access” when I add an item to the Checklist.

I tried to ObserveOn other threads cause maybe the error comes from mix between the UI and the background threads but it doesn’t work. Maybe I don’t use Rx like I would be in that particular case?

Any help would be much appreciate.

EDIT after your answers:

Here is a code which works great!

public void GetData()
{
    Observable.Start(() => LoadData())
    .ObserveOnDispatcher()
    .Subscribe(list =>
    {
        foreach (Item it in list)
        {
            this.Checklist.Add(it);
        }
    });
}

public ObservableCollection<Item> LoadData()
{
    var results = new ObservableCollection<Item>();

    using (ItemDataContext context = new ItemDataContext(_connectionString))
    {
        //Loading

        var contextItems = from i in context.Items
                           select i;

        foreach (Item it in contextItems)
        {
            results.Add(it);
        }
    }

    return results;
}

As you see I didn’t use correctly before. Now I can use a ObservableCollection and use it in the Susbscribe. It’s perfect! Thanks a lot!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T22:41:55+00:00Added an answer on June 8, 2026 at 10:41 pm

    There appears to be no asynchronicity in your code (save the BeginInvoke, which I dont think is doing what you think it is doing).

    I assume that you want to use Rx because your code is all blocking at the moment and the UI is unresponsive while the connection to the database is made and the data is loaded 🙁

    What you want to do is perform the “heavy lifting” on a background thread and then once you have the values just add them to the ObservableCollection on the Dispatcher. You can do this one of three ways:

    1. Return the entire collection in one go. You then loop through the list with a foreach loop adding to the ObservableCollection. This has the potential downside of blocking the UI (unresponsive app) if the list is too large
    2. Return the collection one value at a time, adding each item to the ObservableCollection in an independent call to the dispatcher. This will keep the UI responsive but can take much longer to complete
    3. Return the collection in buffered chunks and try to get the best of both worlds

    The code you want may look like this

    public IList<Item> FetchData()
    {
      using (ItemDataContext context = new ItemDataContext(_connectionString))
      {
        //....
        var results = new List<Item>();
        foreach (Item it in contextItems)
        {
          results.Add(it);
        }
        return results;
      }
    }
    public void LoadData()
    {
      Observable.Start(()=>FetchData())
                .ObserveOnDispatcher()
                .Subscribe(list=>
                  {
                    foreach (Item it in contextItems)
                    {
                      this.Checklist.Add(it);
                    }
                  });
    }
    

    The code ain’t ideal for Unit testing, but it appears that this is not of interest to you any way (static members, VM with DB connectsions etc..) so this might just work?!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to count the length of a string with PHP. The string
I want use html5's new tag to play a wav file (currently only supported
I would like to run a str_replace or preg_replace which looks for certain words
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
I have some data like this: 1 2 3 4 5 9 2 6
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.