Skip to content

Instantly share code, notes, and snippets.

import androidx.lifecycle.ViewModel as AndroidXViewModel
import androidx.lifecycle.viewModelScope as androidXViewModelScope
actual abstract class ViewModel actual constructor() : AndroidXViewModel() {
actual val viewModelScope: CoroutineScope = androidXViewModelScope
actual override fun onCleared() {
super.onCleared()
}
}
actual abstract class ViewModel {
actual val viewModelScope = MainScope()
protected actual open fun onCleared() {}
fun clear() {
onCleared()
viewModelScope.cancel()
}
}
expect abstract class ViewModel() {
val viewModelScope: CoroutineScope
protected open fun onCleared()
}
// In an activity:
private val presenter by retain { entry ->
// entry exposes the viewModelScope, savedStateHandle, and a way to listen to onClear()
MyPresenter()
}
// Or in a composable, implicitly:
val presenter = retain { MyPresenter() } // this will look at LocalViewModelStoreOwner.current
// Or explicitly:
val activity = ...
private let greetingHandler = InjectApplicationComponent()
.greetingHandlerCreator("assisted arg!")
// iOS source set
interface PlatformComponent {
@Provides fun IosPlatformGreeter.bind(): PlatformGreeter = this
}
// Android source set
interface PlatformComponent {
@Provides fun AndroidPlatformGreeter.bind(): PlatformGreeter = this
}
 class MainActivity : ComponentActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
-    val greetingHandler = applicationComponent.greetingHandlerFactory.create(assistedArg = "this is an assisted arg")
+    val greetingHandler = applicationComponent.greetingHandlerCreator("this is an assisted arg")
 class GreeterApplication : Application(), ApplicationComponentProvider {
    override val component by lazy(LazyThreadSafetyMode.NONE) {
-     DaggerApplicationComponent.factory().build(applicationContext)
+     ApplicationComponent::class.create(applicationContext)
    }
  }
- typealias SpecialGreeting1 = String
- typealias SpecialGreeting2 = String
+ @JvmInline value class SpecialGreeting1(val value: String)
+ @JvmInline value class SpecialGreeting2(val value: String)
...
- fun provideSpecialGreeting1(): SpecialGreeting1 = "Heeeeey"
+ fun provideSpecialGreeting1(): SpecialGreeting1 = SpecialGreeting1("Heeeeey")
...
- platformGreeter().greet(finalGreeting = specialGreeting1)
@Component @Singleton
  abstract class ApplicationComponent(
    @get:Provides val context: Context,
- ) : GreetingComponent {
-   abstract val greetingHandlerCreator: (String) -> GreetingHandler
- }
+ ) : GreetingComponent