Do comprehensions for Kotlin and 3rd party libraries [STABLE]

Overview

Komprehensions

Komprehensions is a library to reduce boilerplate and simplify your call chains.

Rationale

As your code starts getting more and more functional, you find that you want to chain multiple statements by helpers like let. This causes indentation levels to go quite high, and would often require that you split the code in several methods just to keep it readable.

fun calculateDoubles(calcParams: Params) =
    calcParams
            .let { params ->
                defrombulate(params.first, param.second)
                        .let { result ->
                            gaussianRoots(result)
                                    .let { grtts ->
                                        storeResult(params.first, params.second, result, grtts)
                                    }
                        }
            }

Comprehensions are a language feature that allow you to define such a chain in a way where every observable is a function at topmost indentation, yet still contains all the parameters received in the previous functions.

Usage

Let

Komprehensions contains functions doLet() for let(). Each takes from 2 to 9 function each with an increasing number of parameters, and returns an object of the type of the return of the last function.

fun calculateDoubles(calcParams: Params) =
    // chained with let()
    doLet(
        { calcParams },
        { params -> defrombulate(params.first, param.second) },
        { params, result -> gaussianRoots(result) },
        { params, result, grtts -> storeResult(params.first, params.second, result, grtts) }
    )

Chainable

Komprehensions contains functions doChainable() for interface Chainable. Each takes from 2 to 9 function each with an increasing number of parameters, and returns a Chainable.

It's functionally similar to let but it's limited to types that are marked as Chainable. The recommended usage is to annotate sealed classes with it to indicate that they can be transformed between them. An example is available in this link with a longer description given by "A Domain Driven approach to Kotlin's new types".

A special thanks to @Takhion for simplifying my initial implementation.

map

Komprehensions contains functions doMapIterable() for map() chaining of Iterable. Each takes from 1 to 9 function each with an increasing number of parameters, and returns an Iterable of the type of the return of the last function.

flatMap

Komprehensions contains functions doFlatMapIterable() for flatMap() chaining of Iterable. Each takes from 1 to 9 function each with an increasing number of parameters and returns an Iterable, then flattens the return into an Iterable of the type of the return of the last function.

Komprehensions-rx

Komprehensions-rx is an extension module that allows chaining of RxJava Observables. It is available for both RxJava 1 and 2.

Map comprehensions

Komprehensions-rx contains functions doFlatMap() for flatMap(), doConcatMap() for concatMap(), doSwitchMap() for switchMap(). Each takes from 1 to 9 function each with an increasing number of parameters, and returns an Observable of the type of the return of the last function.

Observable<String> getUserFriends =
    // chained with flatMap()
    KomprehensionsRx.doFlatMap(
        { profileClicks() },
        { position -> getUserFromProfile(position) },
        { position, user -> requestFriendListForUser(position, user.id) },
        { position, user, friends -> storeUserAndFriends(user, friends) },
        { position, user, friends, result -> toUserDisplayString(position, user, friends, result) }
    );

Compose comprehensions

Komprehensions-rx contains functions doCompose() for compose(). Each takes from 1 to 9 Transformer<T, U> (RxJava 1.X) or ObservableTransformer<T, U> (RxJava 2.X), and returns an Observable of the type of the return of the last one.

Observable<List<Siblings>> getRelatives =
    // chained with compose()
    KomprehensionsRx.doCompose(
        { requestRelative("12345") },
        validate(),
        assureThreads(Schedulers.io(), AndroidSchedulers.main()),
        respectLifecycle(activity),
        toUILayerModel(),
        groupSiblings()
    );

Observable<RelativeDto> requestRelative(String id) { /* ... */ }

ObservableTransformer<RelativeDto, RelativeDto> validate() { /* ... */ }

ObservableTransformer<RelativeDto, RelativeDto> assureThreads(Scheduler in, Scheduler out) { /* ... */ }

ObservableTransformer<RelativeDto, RelativeDto> respectLifecycle(Activity activity) { /* ... */ }

ObservableTransformer<RelativeDto, Relative> toUILayerModel() { /* ... */ }

ObservableTransformer<Relative, List<Siblings>> groupSiblings() { /* ... */ }

Komprehensions-reactor

Komprehensions-reactor is an extension module that allows chaining of Project Reactor Flux and Mono operators.

Map comprehensions

Komprehensions-reactor contains functions doFlatMap() for flatMap(), doConcatMap() for concatMap(), doSwitchMap() for switchMap(). Each takes from 1 to 9 function each with an increasing number of parameters, and returns an Flux of the type of the return of the last function. It also contains functions doFlatMapMono() for flatMap() on the Mono operator. Each takes from 1 to 8 function each with an increasing number of parameters, and returns a Mono of the type of the return of the last function.

Flux<String> getUserFriends =
    // chained with flatMap()
    KomprehensionsReactor.doFlatMap(
        { profileClicks() },
        { position -> getUserFromProfile(position) },
        { position, user -> requestFriendListForUser(position, user.id) },
        { position, user, friends -> storeUserAndFriends(user, friends) },
        { position, user, friends, result -> toUserDisplayString(position, user, friends, result) }
    );

Distribution

Add as a dependency to your build.gradle

repositories {
    ...
    maven { url "https://jitpack.io" }
    ...
}
    
dependencies {
    ...
    compile 'com.github.pakoito.Komprehensions:komprehensions:1.3.2'

    // Extensions for RxJava 1.X
    compile 'com.github.pakoito.Komprehensions:komprehensions-rx:1.3.2'

    // Extensions for RxJava 2.X
    compile 'com.github.pakoito.Komprehensions:komprehensions-rx2:1.3.2'

    // Extensions for Reactor
    compile 'com.github.pakoito.Komprehensions:komprehensions-reactor:1.3.2'
    ...
}

or to your pom.xml

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

<dependency>
    <groupId>com.github.pakoito.Komprehensions</groupId>
    <artifactId>komprehensions</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>com.github.pakoito.Komprehensions</groupId>
    <artifactId>komprehensions-rx</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>com.github.pakoito.Komprehensions</groupId>
    <artifactId>komprehensions-rx2</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>com.github.pakoito.Komprehensions</groupId>
    <artifactId>komprehensions-reactor</artifactId>
    <version>1.3.2</version>
</dependency>

Contributions

PRs and suggestions for new features welcome.

If you have any core function that is chainable, please PR against the main module. If the function is contained in any 3rd party dependency, create a separate module and PR it instead.

For any error report please send an issue with a full stack trace and reproduction steps.

License

Copyright (c) pakoito 2016

The Apache Software License, Version 2.0

See LICENSE.md

You might also like...
Automatically empty the trash in all of your Plex libraries

Plex Auto Trash Automatically empty the trash in all of your Plex libraries. If you disable automatic trash emptying (and you probably should) trash s

Account-lib - A suite of libraries to facilitate the usage of account-sdk

Usage Clone this repository (skip this step if the repo is on your local machine). The default branch is fine. git clone https://github.com/AFBlockcha

The AppMetrica Push SDK is a set of libraries for working with push notifications.
The AppMetrica Push SDK is a set of libraries for working with push notifications.

Flutter AppMetrica Push AppMetrica Push SDK — это набор библиотек для работы с push-уведомлениями. Подключив AppMetrica Push SDK, вы можете создать и

🧸 A multiplatform coroutine-based wrapper for popular platform-specific Redis client libraries

🧸 rekt ⚠️ WARNING! This project is experimental and may be missing essential features. Please let us know if you found any issues or have any suggest

🧸 A multiplatform coroutine-based wrapper for popular platform-specific Redis client libraries

🧸 rekt ⚠️ WARNING! This project is experimental and may be missing essential features. Please let us know if you found any issues or have any suggest

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web 본 저장소는 코틀린 멀티플랫폼 기반 웹 프로그래밍 워크숍(강좌)을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 워크숍 과정에서 코틀린 멀티플랫폼을 기반으로 프론트엔드(front-end)는 Ko

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform 본 저장소는 INFCON 2022에서 코틀린 멀티플랫폼 기반 웹 프로그래밍 핸즈온랩을 위해 작성된 템플릿 프로젝트가 있는 곳입니다. 핸즈온 과정에서 코틀린 멀티플랫폼을

Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in Kotlin with Jetpack Compose and a backed in Kotlin hosted on AppEngine.

Conferences4Hall Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in K

A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

Comments
  • Generate source artifact.

    Generate source artifact.

    I have absolutely no idea how to test it. I made sure Gradle works, project still builds, nothing changed.. but source generation and being able to peek into sources wasn't tested.

    opened by bernaferrari 0
Releases(1.3.2)
  • 1.3.2(Apr 16, 2019)

  • 1.3.1(Apr 8, 2019)

  • 1.3.0(Feb 24, 2017)

    Kotlin has updated to 1.0.6, and RxJava 1 to 1.2.7.

    Due to the overwhelming feedback I've renamed all functions from their short form into the full name.

    • doL is now doLet
    • doCh is now doChainable
    • doMI is now doMapIterable
    • doFMI is now doFlatMapIterable

    Komprehensions-rx

    • doFM is now doFlatMap
    • doCM is now doConcatMap
    • doSM is now doSwitchMap
    • doCo is now doCompose
    Source code(tar.gz)
    Source code(zip)
  • 1.2.1(Feb 19, 2017)

  • 1.2.0(Feb 19, 2017)

    It adds top level comprehension functions for the following chainable methods:

    Komprehensions

    • let for any type
    • new interface Chainable
    • Iterable#map
    • Iterable#flatMap

    KomprehensionsRx 1 and 2

    For Observable#

    • flatMap
    • switchMap
    • concatMap
    • compose
    Source code(tar.gz)
    Source code(zip)
Owner
Paco
@pacoworks
Paco
Paper plugin for third-party AuthMe logins

Interactive Login Paper plugin that extends AuthMe (or AuthMeReloaded) with interactive third-party logins. Currently supports Discord as an external

Leonardo Giovanni Scur 0 Nov 25, 2021
Run Kotlin/JS libraries in Kotlin/JVM and Kotlin/Native programs

Zipline This library streamlines using Kotlin/JS libraries from Kotlin/JVM and Kotlin/Native programs. It makes it possible to do continuous deploymen

Cash App 1.5k Dec 30, 2022
The most essential libraries for Kotlin Multiplatform development

Essenty The most essential libraries for Kotlin Multiplatform development. Supported targets: android jvm js (IR and LEGACY) iosArm64, iosX64 watchosA

Arkadii Ivanov 218 Jan 3, 2023
🔨 Template for easy hosting of your Java/Kotlin libraries on GitHub

?? kotlin-jvm-library-template Another template for easy hosting your Java/Kotlin libraries on GitHub. Features boilerplate for Kotlin/Java projects w

Viktor 0 Jan 7, 2022
An awesome collaborative collection of Kotlin Multiplatform libraries

Awesome Kotlin Multiplatform Awesome Projects Updated 33 November 21, 2021 Contents Guides Dependency Injection Database NoSQL SQL Extension Reactive

Matteo Crippa 5 Dec 12, 2022
Trikot / kotlin multiplatform libraries

Trikot / kotlin multiplatform libraries Table of contents Introduction Modules Samples License Introduction Trikot is a framework that helps building

Mirego 56 Dec 15, 2022
Android project setup files when developing apps from scratch. The codebase uses lates jetpack libraries and MVVM repository architecture for setting up high performance apps

Android architecture app Includes the following Android Respository architecture MVVM Jepack libraries Carousel view Kotlin Kotlin Flow and Livedata P

null 2 Mar 31, 2022
An awesome list that curates the best KMM libraries, tools and more.

Awesome KMM Kotlin Multiplatform Mobile (KMM) is an SDK designed to simplify creating cross-platform mobile applications. With the help of KMM, you ca

Konstantin 994 Dec 28, 2022
A personal project made using Jetpack Compose, Clean-MVVM architecture and other jetpack libraries

A basic CRUD for recording your personal credit and debit transactions. Made using Jetpack Compose, Clean-MVVM and other Jetpack libraries, incorporated with Unit Tests.

Shoaib Ahmed 3 Dec 6, 2022
Boilerplate code for implementing MVVM in Android using Jetpack libraries, coroutines, dependency injection and local persistance

MVVM Foundation This projects aims to speed up development of Android apps by providing a solid base to extend Libraries Jetpack Fragment Material3 :

Gabriel Gonzalez 2 Nov 10, 2022