I was drafting an article on Kotlin coroutines for a while, but it is very far from being finished, so... a thread🙃

The point in question was: can we actually do something with coroutines while being (artificially) restrained to a standard library?
The short answer is: Yes!!! But why?

The longer answer is: start by reading about coroutine primitives from the official KEEP: https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md
and get some idea about compiler transforms from here:
https://proandroiddev.com/how-do-coroutines-work-under-the-hood-803e6e9da8bb
From a high level, there are quite many things that you are omitting with the "kotlinx" part:
- Most of the "structured concurrency" stuff
- Cancellation in general
- Multithreading with Dispatchers
- Many more small and big QoL things.
The good news is that you can reimplement most of them and even interface all of this with your framework of choice (RxJava, anyone?) while avoiding the parts you don't need.
- Some portion of structured concurrency can be achieved by carefully threading CoroutineContext through startCoroutine calls and wiring cancellation to callbacks / "insert your type of Future here"
- Cancellation is interesting, because you can only use Result (success/failure) to express coroutine execution. That's why we have a CancellationException thing which expresses another type of failure (abandoning execution).
- Multithreading is easy with ContinuationInterceptor ( https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md#continuation-interceptor) until you realize that now every bit of state you had in different primitives for interfacing callbacks has to be thread-safe.

(My advice is to use atomicfu, lay on the floor and cry)
Somewhere around this moment I realized that maybe going through this ordeal wasn't the brightest of my ideas.
There's no point in reimplementing the wheel without destination in mind, and creating a new coroutines library clearly wasn't mine.
If you think that you only need some of those things I mentioned above, consider using more bare-bone coroutines.

I can imagine emulating async/await mechanism for JS promises without increase in bundle size...
...or spacing out RxJava's flatMaps at the cost of two methods (and a class for each suspend function ¯\\_(ツ)_/¯) in your DEX files.
If you are looking for somebody who actually did it: @arrow_kt used suspend functions (stdlib only!!!) as a basis for ArrowFx: https://arrow-kt.io/docs/fx/coroutines/
You can follow @shikasd_.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.