Skip to content

Simplify the processing of sealed class/interface

License

Notifications You must be signed in to change notification settings

tkhskt/shiirudo

Repository files navigation

shiirudo

Generates DSL to simplify processing branching by when expressions in sealed class/interface.

Setup

Refer to the KSP quickstart guide to make KSP available for your project.

Installation

Repository is now Jitpack:

repositories {
   maven { url "https://jitpack.io" }
}

Check the latest-version

implementation "com.tkhskt:shiirudo:[latest-version]"
ksp "com.tkhskt:shiirudo:[latest-version]"

Usage

Annotate the target sealed class/interface with the Shiirudo annotation.

@Shiirudo
sealed interface Event {
    object ShowDialog : Event
    object CloseDialog : Event
    object ShowToast : Event
}

When the project is built, shiirudo methods corresponding to subclasses of the annotated class are generated.

The shiirudo method can be used as follows.

fun handleEvent(event: Event) {
    event.shiirudo()
        .isShowDialog {

        }
        .isCloseDialog {

        }
        .isElse {

        }.execute()
}

// or

fun handleEvent(event: Event) {
    eventShiirudo {
        event
    }.isShowDialog {

    }.isCloseDialog {

    }.isElse {

    }.execute()
}

// or

fun handleEvent(event: Event) {
    event.shiirudo {
        isShowDialog {

        }
        isCloseDialog {

        }
        isElse {

        }
    }
}

Use with Flow

You can use shiirudo when you collect Flow as follows.

private suspend fun Flow<Event>.collectEvent(
    handler: EventShiirudoBuilder.() -> Unit,
) {
    collect {
        it.shiirudo(handler)
    }
}

fun handleEvent(eventFlow: Flow<Event>) {
    eventFlow.collectEvent {
        isShowDialog {

        }
        isCloseDialog {

        }
    }
}

Name Resolution

The code generated from the nested sealed class/interface and its subclasses is name resolved as follows.

class SampleViewModel : ViewModel() {

    @Shiirudo
    sealed interface Event {
        interface Dialog {
            object Show : Event
            object Close : Event
        }
        object ShowToast : Event
    }
}

fun handleEvent(event: SampleViewModel.Event) {
    event.shiirudo {
        isDialogShow {

        }
        isDialogClose {

        }
        isShowToast {

        }
    }
}

Examples

See the sample project.

License

MIT

About

Simplify the processing of sealed class/interface

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages