-
-
Notifications
You must be signed in to change notification settings - Fork 59
Provide Postgrest instance
To use Postgrest instance in your Android app, you can either provide the instance by injecting it to your class or create new one whenever you need. It is recommended that we should provide dependencies via DI framework like Dagger or Hilt instead of create a new instance everytime we need.
In modern Android development, we can Hilt to provide instance of Postgrest as a singleton object. The reason of doing this is that we only need to instanciate Postgrest object once with initial config and it will retained in application lifecycle, also we need to mock it to perform testing.
@InstallIn(SingletonComponent::class)
@Module
object SupabaseModule {
}
Use @InstallIn(SingletonComponent::class)
to tie the module to the singleton scope so that we can access anywhere in our app.
As you might know, Supabase offer lots of services, including Postgrest for database, Storage, Go True for authentication,... It's a good practice these kinds of object in one place which is our SupbaseModule so that in the future, if we want to use them, just provide them here.
Inside SupabaseModule, provide Postgrest instance by annotating with @Provides
and @Singleton
. The whole module will look like this
@InstallIn(SingletonComponent::class)
@Module
object SupabaseModule {
@Provides
@Singleton
fun provideSupabaseDatabase(): Postgrest {
val postgrest = standaloneSupabaseModule(
Postgrest,
url = BuildConfig.SUPABASE_URL,
apiKey = BuildConfig.API_KEY
)
return postgrest
}
}
At this point, you're able to inject Postgrest in your class. Because this instance is for API service, I would like to inject it to repository layer.
class CategoryRepositoryImpl @Inject constructor(
private val categoryDao: CategoryDao,
private val supabasePostgrest: Postgrest
) : CategoryRepository {