How to get Executor for main thread on API level < 28 How to get Executor for main thread on API level < 28 multithreading multithreading

How to get Executor for main thread on API level < 28


You can use code snippet from retrofit https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Platform.java

public class MainThreadExecutor implements Executor {    private final Handler handler = new Handler(Looper.getMainLooper());    @Override     public void execute(Runnable r) {        handler.post(r);    }}   


You can use new HandlerExecutor(Looper.getMainLooper()); from com.google.android.gms.common.util.concurrent.HandlerExecutor...in the end it's the same answer as atarasenko.

I added an extension in Kotlin for that:

fun Context.mainExecutor(): Executor {    return if (VERSION.SDK_INT >= VERSION_CODES.P) {        mainExecutor    } else {        HandlerExecutor(mainLooper)    }}