AndroidSupportComponents icon indicating copy to clipboard operation
AndroidSupportComponents copied to clipboard

Missing generic Android.Arch.Lifecycle.IObserver<>

Open IngweLand opened this issue 6 years ago • 2 comments

Xamarin.Android Version (eg: 6.0):

10.0

Operating System & Version (eg: Mac OSX 10.11):

Win 10

Support Libraries Version (eg: 23.3.0):

28.0.0.3 Xamarin.Android.Arch.Work.Runtime 1.0.0.0

Describe your Issue:

The progress and the result of Worker can be retrieved by observing the WorkInfo. https://developer.android.com/topic/libraries/architecture/workmanager/advanced#params

The Java code sample

WorkManager.getInstance(myContext).getWorkInfoByIdLiveData(myWorkRequest.getId())
    .observe(lifecycleOwner, info -> {
                    // ... do something with the result ...
         }
    });

C# code which will not compile

WorkManager.Instance.GetWorkInfoByIdLiveData(myWorkRequest.Id)
                .Observe(lifecycleOwner, info => {
                    // ... do something with the result ...
         });

However, same code cannot be recreated in Xamarin, because generic version of IObserver<> is missing.The non-generic version of IObserver is present in Android.Arch.Lifecycle namespace.

Workaround:

using Android.Arch.Lifecycle;
using AndroidX.Work;
using Java.Lang;

public class MyWorkManager : Object, IObserver
    {
        public void OnChanged(Object p0)
        {
            var wi = p0 as WorkInfo;
            if (wi == null)
            {
                return;
            }

             // ... do something with the result ...
        }

        public void StartWork()
        {
             OneTimeWorkRequest myRequest =
                OneTimeWorkRequest.Builder.From<MyWorker>().Build();

            WorkManager.Instance.Enqueue(myRequest);
            WorkManager.Instance.GetWorkInfoByIdLiveData(myRequest.Id)
                .Observe(lifecycleOwner, this);
        }
    }

Steps to Reproduce (with link to sample solution if possible):

Include any relevant Exception Stack traces, build logs, adb logs:

IngweLand avatar Oct 04 '19 11:10 IngweLand

Hello, any updates on this?

JFenlon avatar Jan 12 '20 17:01 JFenlon

FYI, found a workaround the null WorkInfo issue for the time being:

public void OnChanged(Java.Lang.Object p0)
{
	var p0List = p0 as IEnumerable;
	
	foreach (var item in p0List )
	{
		var workInfo = item as WorkInfo;

		if (workInfo != null && workInfo.GetState() == WorkInfo.State.Succeeded)
		{
                     // Handle Success state here
		}
	}
}

JFenlon avatar Jan 13 '20 16:01 JFenlon