Jump to content

Lambda Support for Wait Conditions (Make your code cleaner!)


The Viking

Recommended Posts

OVERVIEW

 

With this snippet, you can avoid writing in-line anonymous classes for wait conditions. This makes code cleaner and speeds up development time.

 

Before, you would have to do this: 

new ConditionalSleep(5000){
	@ Override
	public boolean condition() throws InterruptedException
	{
		return !myPlayer().isMoving();
	}
}.sleep();

Now you can do this:

Timing.waitCondition(() -> !myPlayer().isMoving(), 5000);

Or, if you want to specify cycle time for checking condition:

Timing.waitCondition(() -> !myPlayer().isMoving(), 600, 5000);

IMPLEMENTATION

 

Add my Timing class w/ static util methods to your API

package viking.api;

import java.util.function.BooleanSupplier;
import java.util.concurrent.TimeUnit;

import org.osbot.rs07.utility.ConditionalSleep;

/**
 * Static utility class with various methods that are related
 * to time / timing.
 * 
 * @author The Viking
 *
 */
public class Timing
{
	/**
	 * Calculates the time, in ms, from a specific mark
	 * 
	 * @param mark The initial time mark we're calculating from
	 * @return The time, in ms, from the provided mark
	 */
	public static long timeFromMark(long mark)
	{
		return System.currentTimeMillis() - mark;
	}
	
	/**
	 * Returns the current time in ms. Essentially just a shorter
	 * wrapper for System.currentTimeMillis()
	 * 
	 * @return The current time, in ms
	 */
	public static long currentMs()
	{
		return System.currentTimeMillis();
	}
	
	/**
	 * Converts a time, in ms, to a pretty String in hh:mm:ss:SSS format
	 * 
	 * @param ms The time, in ms, to convert
	 * @return A string representing the current time
	 */
	public static String msToString(long ms)
	{
		return String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(ms),
			    TimeUnit.MILLISECONDS.toMinutes(ms) % TimeUnit.HOURS.toMinutes(1),
			    TimeUnit.MILLISECONDS.toSeconds(ms) % TimeUnit.MINUTES.toSeconds(1));
	}
	
	/**
	 * This method waits for a specific condition
	 * to be true within a maximum amount of time. Your
	 * basic conditional sleep. This method uses the BooleanSupplier functional interface, so it provides lambda support
	 * 
	 * @param condition the condition to wait for
	 * @param cycleTime the time, in ms, between condition checks
	 * @param timeout the maximum time to wait for the condition to be true
	 * @return true if the condition was met within the threshold, or false if the timeout was exceeded
	 */
	public static boolean waitCondition(BooleanSupplier condition, int cycleTime, int timeout)
	{
		return new ConditionalSleep(timeout, cycleTime)
		{
			@Override
			public boolean condition()
			{
				try
				{
					return condition.getAsBoolean();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				
				return false;
			}
			
		}.sleep();
	}
	
	/**
	 * This method waits for a specific condition to be true within a maximum amount of time. Your
	 * basic conditional sleep. This method uses the BooleanSupplier functional interface, so it provides lambda support
	 * 
	 * @param condition the condition to wait for
	 * @param timeout the maximum time to wait for the condition to be true
	 * @return true if the condition was met within the threshold, or false if the timeout was exceeded
	 */
	public static boolean waitCondition(BooleanSupplier condition, int timeout)
	{
		return waitCondition(condition, 20, timeout);
	}

}

Edited by The Viking
  • Like 13
Link to comment
Share on other sites

  • 2 weeks later...
On 2/3/2017 at 4:21 AM, Satire said:

@nosepicker Here's your lambda support. Thank Viking :P 

 

EDIT: Seems you've already seen it :D

 

EDIT2: Good job @The Viking. I used this and it makes things so much better. Code is much cleaner now. I may use this in all my projects :D

Glad you are getting use out of it!

Link to comment
Share on other sites

  • 1 month later...
  • 3 months later...

Please stop using the callable interface for things like this

Callable is reserved for concurrent programming hence why it's in the java.util.concurrent package and not the java.util.function package.

Want to get 'functional'? Use the java.util.function package (https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html). You more specifically probably should use a BooleanSupplier in this case.

Oh and by the way, curly braces usually aren't newlined in Java (this isn't C# !!!), I recommend you drop this habit asap .

11/10 for effort in terms of documentation and overal cleanness of you code though :)!

 

 
 
 
 

 

 

  • Like 2
Link to comment
Share on other sites

On 7/14/2017 at 3:24 PM, Botre said:

Please stop using the callable interface for things like this

Callable is reserved for concurrent programming hence why it's in the java.util.concurrent package and not the java.util.function package.

Want to get 'functional'? Use the java.util.function package (https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html). You more specifically probably should use a BooleanSupplier in this case.

Oh and by the way, curly braces usually aren't newlined in Java (this isn't C# !!!), I recommend you drop this habit asap .

11/10 for effort in terms of documentation and overal cleanness of you code though :)!

 

 
 
 
 

 

 

Callable was only implemented due to a suggestion above, and this was before I knew BooleanSupplier even existed. I will update the thread to use BooleanSupplier instead.

Your comment on brace placement is completely subjective. I really hope you won't try to argue otherwise. Sure, there is a 1997 article our there where Oracle states that braces on the same line is the convention, however it's pretty much universally known as a personal choice (as long as you're consistent).

Thank you for the feedback however, I really do appreciate it.

Link to comment
Share on other sites

10 hours ago, The Viking said:

Callable was only implemented due to a suggestion above, and this was before I knew BooleanSupplier even existed. I will update the thread to use BooleanSupplier instead.

Your comment on brace placement is completely subjective. I really hope you won't try to argue otherwise. Sure, there is a 1997 article our there where Oracle states that braces on the same line is the convention, however it's pretty much universally known as a personal choice (as long as you're consistent).

Thank you for the feedback however, I really do appreciate it.

You are sharing this snippet for other people to integrate it in their code.

Most people don't newline.

Therefore you are introducing inconsistencies in other people's code base by not respecting the dominant code-style.

Code style always is a personal choice, that doesn't mean you shouldn't be pragmatic about it.

You are the 1% in this case, don't expect the 99% to deviate from the convention just 'because of  subjectivity'.

I know, I know, I'm a pain in the ass.

public class fuckConventions() 

{

public

fuckConventions()

{

// lower*burp*case constructor bro i dont give a fuuuuuuuuuuuck

}

public void UpperCaseMethodsBoy()

{

// hahahaha nope not a constructor just a regular method wubba lubba dub dub

}

}

 

Edited by Botre
  • Like 1
Link to comment
Share on other sites

9 hours ago, Botre said:

You are sharing this snippet for other people to integrate it in their code.

Most people don't newline.

Therefore you are introducing inconsistencies in other people's code base by not respecting the dominant code-style.

Code style always is a personal choice, that doesn't mean you shouldn't be pragmatic about it.

You are the 1% in this case, don't expect the 99% to deviate from the convention just 'because of  subjectivity'.

I know, I know, I'm a pain in the ass.


public class fuckConventions() 

{

public

fuckConventions()

{

// lower*burp*case constructor bro i dont give a fuuuuuuuuuuuck

}

public void UpperCaseMethodsBoy()

{

// hahahaha nope not a constructor just a regular method wubba lubba dub dub

}

}

 

Not only are your percentages completely anecdotal and have no actual proof to back them up, but the "example" you gave is a complete exaggeration and misrepresentation of my point.  If you would bother to do some actual research, you would see that your claim is way off. Far cry from the "1%" number you gave.

1dc30d92798e0920bc9cfb3f74b331af.png

Source: https://github.com/outsideris/popularconvention (Somebody analyzed code conventions across commits on GitHub)

You're once again off base with your statement that "you are introducing inconsistencies in other people's code base by not respecting the dominant code-style.". What about the 37% of people that use new line braces? Are you introducing inconsistencies into their code base if you release a snippet? No, because they should adjust it to fit with their own preference. I wouldn't consider that a difficult task.

As long as they are consistent within their own code-base, it doesn't matter which style they use. This is even true at the corporate level, where conventions can vary from company to company. For example, brace placement, tabs vs spaces, line length, variable naming and exception catch clauses (empty catch blocks, swallowing exceptions) are just some of the nuances that can vary from company to company. It isn't a problem though, since their specific rules apply to their specific code base.

Edited by The Viking
  • Like 3
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...