Search code examples
c#windows-phone-8akavache

What's the right way to use Akavache's LoadImageFromUrl in a Windows Phone project?


The goal is to asynchronously fetch an image from a url and then set it to a BitmapSource viewmodel property (which is databound in a view).

I can use LoadImageFromUrl to get a Splat.IBitmap, but I can't figure out how to connect that to a BitmapSource. In fact, I'm not sure that I'm using this method correctly at all.

Here's what I've got:

using Akavache;
using System.Reactive.Linq;

// ...others...

var myViewModel = ...;

var url = @"http://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png";

BlobCache.LocalMachine.LoadImageFromUrl(url, false, 200, 183)
    .ObserveOnDispatcher()

    // up to here, it's fine
    // what goes below is the question

    // I manually instantiate an Action object so as to explicitly pick that override,
    // but LoadImageFromUrl returns an IObservable<Splat.IBitmap>, so I'm not picking the wrong <T> here
    .Subscribe(new Action<Splat.IBitmap>(pic => {
        // haha, nope: myViewModel.someBitmapSource = (BitmapSource)pic);
    }), ex => Debug.WriteLine(ex));

Other things I thought of:

  • Check documentation: none seems to exist that I can find
  • Google around: slim pickings, nothing directly helpful
  • Look to see how this method is used in Akavanche tests: it doesn't appear to be called anywhere
  • Since a Splat-namespace object is returned, check Splat tests/docs: Closer. The splat readme says:

.

// ToNative always converts an IBitmap into the type that the platform
// uses, such as UIBitmap on iOS or BitmapSource in WPF
ImageView.Source = ViewModel.ProfileImage.ToNative();

Great, except ToNative() doesn't make sense in this case because it's not a member of the Splat.IBitmap interface.

And now I'm out of ideas.


Solution

  • ToNative is a Splat extension of the IBitmap interface. Adding a dependency on Splat and using it in this context will make that method available.

    Whether or not that's the Right™ way to do it, I'm not sure.