Skip to content

Instantly share code, notes, and snippets.

@jamie94bc
Created April 20, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamie94bc/7e5836bc798b32e9dfac to your computer and use it in GitHub Desktop.
Save jamie94bc/7e5836bc798b32e9dfac to your computer and use it in GitHub Desktop.
Helper methods for Xamarin.Android to check if IJavaObjects are still alive in the Java VM. Useful for MVVM.
public static class MonoDroidHelper {
/// <summary>
/// Returns true if the current <paramref name="javaObj"/>
/// does not have a <see cref="IJavaObject.Handle"/> to the
/// object in the Java VM.
/// </summary>
public static bool IsInMonoLimbo<T>(this T javaObj) where T : class, IJavaObject {
return javaObj.Handle == IntPtr.Zero;
}
/// <summary>
/// Helper method that checks whether the current <paramref name="javaObj"/>
/// has a <see cref="IJavaObject.Handle"/> to the object in the Java VM, returning
/// null if it does not.
/// </summary>
public static T SafeGet<T>(this T javaObj) where T : class, IJavaObject {
return IsInMonoLimbo(javaObj) ? null : javaObj;
}
/// <summary>
/// Helper method that checks whether the current <paramref name="javaObj"/>
/// has a <see cref="IJavaObject.Handle"/> to the object in the Java VM.
/// </summary>
/// <remarks>
/// Use to resolve exceptions (ArgumentException: 'jobject' must not be IntPtr.Zero.
/// Parameter name: jobject) that commonly occur when view model properties
/// are modified between the Java VM disposing the object and the mono runtime has
/// a chance to disposing the current <paramref name="javaObj"/>.
/// </remarks>
/// <returns>
/// The result of <see cref="getter"/> or null if <see cref="IJavaObject.Handle"/> is
/// equal to <see cref="IntPtr.Zero"/>.
/// </returns>
public static T SafeGet<TJavaObject, T>(this TJavaObject javaObj, Func<TJavaObject, T> getter)
where TJavaObject : class, IJavaObject
where T : class {
return IsInMonoLimbo(javaObj) ? null : getter(javaObj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment