In my project I have a chain of Fragments where each one gets a bitmap, manipulates it, then sends it to another fragment for more processing.
My fragment chain looks like this:
CaptureFragment -> RotateFragment -> CropFragment -> ...
And here's some of the code:
abstract class BaseFragmentInOut<InVM : BitmapViewModel, OutVM : BitmapViewModel>
(private val c1: Class<InVM>, private val c2: Class<OutVM>) : BaseFragment() {
protected lateinit var inViewModel: InVM
protected lateinit var outViewModel: OutVM
fun getInBitmap(): Bitmap = inViewModel.bitmap
fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
inViewModel = getViewModel(c1)
outViewModel = getViewModel(c2)
}
}
sealed class BaseFragment : Fragment() {
protected fun <T: ViewModel>getViewModel(c: Class<T>): T
= ViewModelProviders.of(activity)[c]
}
It leads to fairly awkward code like this since we can't have reified generics in classes:
private typealias RVM = RotateViewModel
private typealias CVM = CropViewModel
class CropFragment: BaseFragmentInOut<CVM, RVM>
(CVM::class.java, RVM::class.java) {
...
}
But the alternative isn't that great either, as it leads to a lot of boilerplate code:
class CropFragment: BaseFragment() {
private lateinit var inViewModel: RotateViewModel
private lateinit var outViewModel: CropViewModel
fun getInBitmap(): Bitmap = inViewModel.bitmap
fun setOutBitmap(bmp: Bitmap) { outViewModel.bitmap = bmp }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
inViewModel = getViewModel()
outViewModel = getViewModel()
}
}
How good of a practice is my approach and are there other better ways to do this?