How to call a function with callbacks in Java, how do I do this in C #?

I am new to Java, but I need to write something like this code in C # (this is a prototype printed by hand to illustrate what I need)

private void ParentFunc() { var worker = new WorkerClass() worker.DoWork(e => console.Write("Progress" + e)); } public class WorkerClass() { public method DoWork(Action<int> callback) { for (int i=1; i<1000; i++) callback.Invoke(i); } } 

A little explanation. I use AsyncTask in android and calling an external class, classified, but would like them to return a signal so that I can publishProgress . I prefer not to install the interface on top of AsyncTask

+6
source share
4 answers

Since closure is not supported, you need to use an interface and an anonymous inner class.

 private void ParentFunc { WorkerClass worker = new WorkerClass(); worker.doWork(new Callback<Integer>() { public void invoke(Integer arg) { System.out.println("Progress" + arg); } }); } public class WorkerClass { public doWork(Callback<Integer> callback) { for (int i=1; i<1000; i++) callback.invoke(i); } } public interface Callback<T> { public void invoke(T arg); } 
+6
source

In java, you use anonymous classes that implement interfaces. This is somewhat more verbose, but it works very well:

 interface MyAction { void doit(String str); } class WorkerClass { void doWork(MyAction action); } void main(String args[]) { WorkerClass worker = new WorkerClass(); worker.doWork(new MyAction { public void doit(String e) { System.out.println("Progress" + e) } }); } 
+5
source

Using the support class:

 interface CallBack<P> { public void callback(P p); } class MyCallBack implements CallBack<String> { public void callBack(String p) { System.out.println(p); } } class WorkerClass { public void doWork(CallBack<String> callback) { // do work callback.callBack("Done!"); } } WorkerClass wc = new WorkerClass(); wc.doWork(new MyCallBack()); 

I am not going to suggest you use anonymous classes because I find them rather verbose until the slicker syntax is available, but it's just a matter of personal taste, I end up losing myself from braces when I use them ..

+4
source

This is possible with java 8. See my answer to a duplicate question:

fooobar.com/questions/44822 / ...

Use the function as an argument:

 import java.util.function.Function; public String applyFunction(Function<String,String> function){ return function.apply("what ever"); } 

Call

 // with someObject.someMethod(String) => String xxx.applyFunction(someObject::someMethod); 
0
source

Source: https://habr.com/ru/post/917467/


All Articles