All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.effect.util.PureClock Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2022, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.effect.util;

import java.time.Duration;
import java.time.OffsetDateTime;

import com.github.tonivade.purefun.Unit;
import com.github.tonivade.purefun.effect.URIO;

public interface PureClock {

   PureClock.Service clock();

  static  URIO currentTime() {
    return URIO.accessM(env -> env.clock().currentTime());
  }

  static  URIO currentDateTime() {
    return URIO.accessM(env -> env.clock().currentDateTime());
  }

  static  URIO sleep(Duration duration) {
    return URIO.accessM(env -> env.clock().sleep(duration));
  }

  interface Service {
    URIO currentTime();
    URIO currentDateTime();
    URIO sleep(Duration duration);
  }

  static PureClock live() {
    return new PureClock() {
      @Override
      public  Service clock() {
        return new Service() {

          @Override
          public URIO currentTime() {
            return URIO.task(System::currentTimeMillis);
          }

          @Override
          public URIO currentDateTime() {
            return URIO.task(OffsetDateTime::now);
          }

          @Override
          public URIO sleep(Duration duration) {
            return URIO.exec(() -> Thread.sleep(duration.toMillis()));
          }
        };
      }
    };
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy