Go-inspired defer-based resource management

Overview

defer-kt

Golang-inspired resource management library.

Add to your project

Gradle

implementation "me.jason5lee:defer:1.0.1"

Gradle Kotlin DSL

implementation("me.jason5lee:defer:1.0.1")

Example

Open two file for reading and writing, print a message before attempting to close them.

deferScope {
    val f1 = File("/path/to/read-file").bufferedReader()
    deferClosing(f1)
    val f2 = File("/path/to/write-file").bufferedWriter()
        .also { deferClosing(it) }
    defer { println("Closing file ...") }
    // Operating f1 and f2
}

Equivilent code using use and try-finally

File("/path/to/read-file").bufferedReader().use { f1 ->
    File("/path/to/write-file").bufferedWriter().use { f2 ->
        try {
            // Operating f1 and f2, with 3 indents instead of 1.
        } finally {
            println("Closing file ...")
        }
    }
}

Example of multiple resources and canceling: suppose you have many output targets, each target has a name. Now you want to implement an object that maintains multiple output target objects, which output information to the corresponding target according to the type of information. You can implement this object like this

data class Message(val type: String, ...)

class OutputTarget(name: String): Closeable {
    override fun close() { ... }
    fun output(message: Message) { ... }
}

class Output(vararg names: String) : Closeable {
    private val outputMap: Map<String, OutputTarget>

    init {
        outputMap = deferScope {
            val outMap = HashMap<String, OutputTarget>(names.size)

            for (name in names) {
                val target = OutputTarget(name)
                // This defer is to close the created target when an exception is thrown
                deferClosing(target)
                outMap[name] = target
            }
            outMap.toMap().also {
                cancelDefers() // cancel all defers because the construction was successful.
            }
        }
    }

    fun output(message: Message) {
        outputMap[message.type]?.output(message)
    }

    override fun close() {
        // You can use deferScope to ensure all targets are closed even if some fail.
        deferScope {
            for (output in outputMap.values) {
                deferClosing(output)
            }
        }
    }
}

Advantage over use and try-finally

Compared to using the use function and try-finally, this library has the following advantages

  1. Less indent, especially if you have multiple resources to close.
  2. Easy to have a variable number of resources.
  3. Provide the cancelDefer method to transfer ownership, i.e. pass the resource to another object and let it close.
You might also like...
YAML-based source-based kotlin module descriptors

kproject - Liberate your Kotlin projects YAML-based source-based kotlin module descriptors that runs on top of gradle. Define your kotlin multiplatfor

Maxibon kata for Kotlin Developers. The main goal is to practice property based testing.
Maxibon kata for Kotlin Developers. The main goal is to practice property based testing.

Kata Maxibon for Kotlin. We are here to practice property based testing. We are going to use KotlinTest to write our tests. We are going to practice p

❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin)  architecture.
❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.

MarvelHeroes MarvelHeroes is a demo application based on modern Android application tech-stacks and MVVM architecture. Fetching data from the network

🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.
🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.

DisneyMotions A demo Disney app using transformation motions based on MVVM architecture. The motion system is included in the 1.2.0-alpha05 released m

A simple demo project based on MVVM clean architecture and material design & animations.
A simple demo project based on MVVM clean architecture and material design & animations.

GithubFollows A simple demo project based on MVVM clean architecture and material design & animations. Architecture Specs & Open-source libraries Mini

TheMovies 🎬 A demo project for The Movie DB based on Kotlin MVVM architecture and material design & animations.
TheMovies 🎬 A demo project for The Movie DB based on Kotlin MVVM architecture and material design & animations.

A simple project for The Movie DB based on Kotlin MVVM clean architecture and material design & animations. How to build on your environment

Kotlin backend based on the Clean Architecture principles. Ktor, JWT, Exposed, Flyway, KGraphQL/GraphQL generated endpoints, Gradle.
Kotlin backend based on the Clean Architecture principles. Ktor, JWT, Exposed, Flyway, KGraphQL/GraphQL generated endpoints, Gradle.

Kotlin Clean Architecture Backend Kotlin backend based on the Clean Architecture principles. The application is separated into three modules: Domain,

A Kotlin-based combo editor
A Kotlin-based combo editor

KtEdit A Kotlin-based combo editor Features Remove Duplicates Shuffle Lines Split File More features will be adding in future updates. Benchmarks Remo

Comments
  • Allow for suspending calls

    Allow for suspending calls

    deferScope {
        defer {
            cleanupTestUser(client, tokenId) // suspending function call
        }
        // do some work here
    }
    

    This code will not work, since defer cannot handle the suspending cleanupTestUser call. Is there a way to add support for this?

    opened by blueneogeo 0
Owner
Jason Dongheng Lee
Love the declarative part of functional programming, interested in the distributed system, blockchain, and domain modeling.
Jason Dongheng Lee
Android-kotlin-lifecycles-management - LifeCycles Management Techniques

Activity Lifecycle - DessertPusher This is the toy app for lesson 4 of the Andro

Jeliel Augusto Mota 0 Jan 8, 2022
Android SharedPreference management library made with kotlin

Kref Android SharedPreference management library made for kotlin Download Use Gradle: allprojects { repositories { ... maven { url

copin-danny 4 Mar 17, 2022
Project created in order to handle account management

Account Service App Aplicação responsável em receber dados de uma conta, validá-los e retornar mensagem de sucesso ou erro. Tecnologias utilizadas - L

Rafael Alberto 0 Dec 14, 2021
Team management service is a production ready and fully tested service that can be used as a template for a microservices development.

team-mgmt-service Description Team management service is a production ready and fully tested service that can be used as a template for a microservice

Albert Llousas Ortiz 18 Oct 10, 2022
LinkHub is a simple and effective link management application that can help you to easily manage your app with no ads!

LinkHub LinkHub is a simple and effective link management application that can help you to easily manage your own links with no ads! Download Screensh

Amr Hesham 71 Dec 17, 2022
A command-line student management system in Kotlin

Student Management System Done as a part of NITK GSDC Android Study Jams 2021 Th

Ranjana Kambhammettu 2 Dec 24, 2021
Pling is a mobile project management application

Pling is a mobile project management application. This application was developed as part of the “Embedded Interface Programming” course. Pling should include all the necessary and minimal features for planning a project, such as creating a project, adding tasks and monitoring progress.

Cassandra CHAUMULON 2 May 16, 2022
Game server management, orchestration, and scaling platform.

Liftgate Game server management, orchestration, and scaling platform. Project Status This project is a W.I.P. This README will be updated once we ente

null 4 Nov 14, 2022
WordGuess - A portuguese game inspired in the world fever wordle game

WordGuess WordGuess is a portuguese game inspired in the world fever wordle game

Anthoni Ipiranga 6 Jul 28, 2022
KotlinDL - High-level Deep Learning Framework written in Kotlin and inspired by Keras

Оригинальный репозиторий https://github.com/JetBrains/KotlinDL KotlinDL: High-le

Temur Yunusov 1 Feb 4, 2022