Suspending functions versus async functions

Some guidelines for the usage of suspending functions instead of async functions are as follows:

The list below uses Job to refer to implementations of it, including Deferred<T>.
  • Generally, it is advised to use suspending functions over async functions to avoid tying the implementation to a Job.
  • Always use suspending functions when defining an interface. Using async functions will force the implementation to return a Job.
  • Likewise, always use a suspending function when defining an abstract function.
  • The more visible a function is, the more important it is to use suspending functions: as already explained, you don't want to be forced to deprecate your public API because the implementation will be changed when you can't—or don't want to— return a Job anymore.
  • The async functions should be limited to private and maybe internal functions. In some scenarios, like the one studied in Chapter 2, Coroutines in Action, having an async function can simplify the code. And having all the code using an async function in a small scope reduces the impact of a refactoring if returning a Job is no longer an option.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.3.175