Search code examples
javaandroiddesign-patterns

Android - How to chain multiple asynchronous methods in a readable manner


On app startup I would like to check multiple conditions like so:

onCreate() {
    result1 = method1();
    result2 = method2(result1);
    result3 = method3(result2);
}

Now these methods depend on user input or network requests so they can't be called like that. Instead, I had to have a layout like this:

onCreate() {
    method1();
}
method1() {
    doStuff();
    somekindOfCallbackThatStuffIsDone(result1) {
        method2(result1);
    };
}
method2(result1) {
    doStuff(result1);
    somekindOfCallbackThatStuffIsDone(result1) {
        method3(result2);
    }
}

Now this still looks kind of okay in the example, but it turned out super messy in code, because there are five of these with multiple conditions on each one. Is there a way for the code to be as easily readible as in the first box?


Solution

  • According to @Phantom Lord this is known as Callback hell and a possible solution in the absence of user interaction are Kotlin Coroutines according to @theapache64.