Cililing

Untitled

Jun 16th, 2021
684
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Callback {
  2.  
  3.     class LoginResult {} // just a mock
  4.  
  5.     // define callback interface - let's make it generic
  6.     // and move it to package like utils
  7.     interface Consumer<T> {
  8.         void accept(T value);
  9.     }
  10.  
  11.  
  12.     interface LoginService {
  13.         // makes a login and post a result on the consumer
  14.         void login(Consumer<LoginResult> consumer);
  15.     }
  16.  
  17.  
  18.     class LoginServiceImpl implements LoginService {
  19.  
  20.         private Auth auth;
  21.  
  22.         @Override
  23.         public void login(Consumer<LoginResult> consumer) {
  24.             auth.login(new Auth.Task<String>() {
  25.                 @Override
  26.                 public void onComplete(String res) {
  27.                     // verify the result etc.
  28.                     // after processing call the consumer
  29.  
  30.                     consumer.accept(new LoginResult());
  31.                 }
  32.             });
  33.         }
  34.     }
  35.  
  36.     // Example method in presenter:
  37.     void login() {
  38.         LoginService service = new LoginServiceImpl();
  39.         service.login(new Consumer<LoginResult>() {
  40.             @Override
  41.             public void accept(LoginResult value) {
  42.                 // check the result
  43.                 handleLogin(value);
  44.             }
  45.         });
  46.     }
  47.    
  48.     // even better! :)
  49.     void login2() {
  50.         LoginService service = new LoginServiceImpl();
  51.         // as you can see this is so common that Java added a support for "method reference"
  52.         // (when the callback/consumer calls a single method we don't need to create an anonymous object
  53.         //  method reference is enough)
  54.         // and login/login2 are the same methods ;)
  55.         service.login(this::handleLogin);
  56.     }
  57.  
  58.     private void handleLogin(LoginResult value) {
  59.         // login handling....
  60.     }
  61.  
  62.    
  63.     // -----------------------------------------------------------------
  64.     // auth service mock
  65.     static class Auth {
  66.         interface Task<T> {
  67.             void onComplete(T res);
  68.         }
  69.         void login(Task<String> t) {}
  70.     }
  71. }
  72.  
  73.  
RAW Paste Data