icerockdev / moko-resources

Resources access for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
1.09k stars 120 forks source link

Implement generation of Strings interface implementation with MR connection #124

Open Alex009 opened 3 years ago

Alex009 commented 3 years ago

In multi-module projects with injection of resources from umbrella module (like https://github.com/icerockdev/moko-template) we have this separation: feature module:

class MyViewModel(
    private val strings: Strings,
) : ViewModel() {
    // ...

    interface Strings {
        val unknownError: StringResource
    }
}

umbrella module (mpp-library - contains resources and generate MR class:

val viewModel = MyViewModel(
    strings = object: ListViewModel.Strings {
        override val unknownError: StringResource
            get() = MR.strings.unknown_error
    }
)

and when we should pass many resources to feature module we do routine work with creating proxy anonymous object.

Alex009 commented 3 years ago

Current idea

Add annotations to moko-resources runtime library

annotation class MRmapping
annotation class MRname(val name: String)

(!) names should be improved

interface in feature module we mark with annotations

@MRmapping
interface Strings {
    @MRname("unknown_error")
    val unknownError: StringResource
}

in umbrella module we connect plugin generator

connect plugin to module, which have access to MR. plugin will generate for all annotated interfaces (from all modules, not only umbrella module) function:

private fun MR.mapping(): ListViewModel.Strings {
    return object: ListViewModel.Strings {
        override val unknownError: StringResource
            get() = MR.strings.unknown_error
    }
}

and we can use already generated proxy:

val viewModel = MyViewModel(strings = MR.mapping())

interfaces should work with all resource types

Alex009 commented 3 years ago

annotation processing - https://github.com/google/ksp/blob/master/docs/quickstart.md

Alex009 commented 3 years ago

can be useful - https://github.com/Tetraquark/KSP-Testing

r4zzz4k commented 2 years ago

By the way, you should consider generating the implementation which can switch resources in runtime during configuration changes, for example, as described at https://github.com/icerockdev/moko-resources/issues/201#issuecomment-922340943. cc @Nailik