package com.novoda.downloadmanager;

import android.support.annotation.Nullable;

import com.novoda.notils.logger.simple.Log;

final class WaitForDownloadServiceThenPerform {

    interface Action<T> {
        T performAction();
    }

    private WaitForDownloadServiceThenPerform() {
        // Uses static factory method.
    }

    static <T> WaitForDownloadServiceThenPerformAction<T> waitFor(@Nullable DownloadService downloadService, Object downloadServiceLock) {
        return new WaitForDownloadServiceThenPerformAction<>(downloadService, downloadServiceLock);
    }

    static class WaitForDownloadServiceThenPerformAction<T> {

        private final DownloadService downloadService;
        private final Object lock;

        WaitForDownloadServiceThenPerformAction(DownloadService downloadService, Object lock) {
            this.downloadService = downloadService;
            this.lock = lock;
        }

        T thenPerform(final Action<T> action) {
            if (downloadService == null) {
                try {
                    synchronized (lock) {
                        lock.wait();
                    }
                } catch (InterruptedException e) {
                    Log.e(e, "Interrupted waiting for download service.");
                }
            }
            return action.performAction();
        }

    }

}

@@ -718,17 +718,32 @@
  Object 
-l
+downloadServiceL
 ock;%0A%0A  
@@ -828,17 +828,32 @@
  Object 
-l
+downloadServiceL
 ock) %7B%0A 
@@ -924,16 +924,46 @@
 his.
-lock = l
+downloadServiceLock = downloadServiceL
 ock;
@@ -1085,18 +1085,146 @@
     
+waitForLock();%0A            %7D%0A            return action.performAction();%0A        %7D%0A%0A        private void waitForLock() %7B%0A            
 try %7B%0A
-    
     
@@ -1249,17 +1249,32 @@
 onized (
-l
+downloadServiceL
 ock) %7B%0A 
@@ -1296,13 +1296,79 @@
     
-    l
+if (downloadService == null) %7B%0A                        downloadServiceL
 ock.
@@ -1414,16 +1414,30 @@
        %7D
+%0A            %7D
  catch (
@@ -1478,20 +1478,16 @@
         
-    
 Log.e(e,
@@ -1549,70 +1549,9 @@
     
-    %7D%0A            %7D%0A            return action.performAction();
+%7D
 %0A   

Add conditional before wait statement in synchronize block.