android-interview-tip
Mohamad Abuzaid 1 year ago
mohamad-abuzaid #android-tips

In Dagger 2 Dependency Injection...

What is the difference between @Provides, @Binds and @Inject ?

-------------------------

[1] @Provides


Annotation for function creating the dependency. Can contain any arbitrary code, where you can define how the dependency should be created.

  • ex: Create and inject Retrofit instance
@Module
class NetworkModule {
  @Provides
  fun provideRetrofit(baseUrl: String): Retrofit {
      return Retrofit.Builder()
          .baseUrl(baseUrl)
          .addConverterFactory(GsonConverterFactory.create())
          .build()
  }
  
  
  @Provides
  fun provideApiService(retrofit: Retrofit): ApiService {
      return retrofit.create(ApiService::class.java)
  }
}


---------------------

[2] @Binds


Just a shortcut used instead of @Provides when you want to bind an interface/abstract class to its implementation.

  • It can take only a single parameter and the type return is the interface/class implemented by the given parameter object.

Note: You can’t use @Provides and @Binds methods together inn the same module class.

@Module
abstract class RepositoryModule {

  @Binds abstract fun bindRepository(repository: RemoteRepository): Repository

  @Binds abstract fun bindDataSource(dataSource: RemoteDataSource): DataSource
}


---------------------

[3] @Inject


Annotates the constructor of a class, if the constructor is public and all its parameters can be provided by Dagger.

class NetworkClient @Inject constructor(
    private val apiService: ApiService,
    private val networkInterceptor: NetworkInterceptor
) {
    
    fun makeRequest(request: Request) {
      // Make the network request using apiService and networkInterceptor objects
    }
}
1
615
Kotlin Coroutines (3/3)

Kotlin Coroutines (3/3)

1675112374.jpg
Mohamad Abuzaid
1 year ago
Introduction to Kotlin Functional Programming (2/3)

Introduction to Kotlin Functional Programming (2/3)

1675112374.jpg
Mohamad Abuzaid
7 months ago
Design Patterns - [1] Creational

Design Patterns - [1] Creational

1675112374.jpg
Mohamad Abuzaid
1 year ago
Effective UI/UX Design in Android Apps (1/3)

Effective UI/UX Design in Android Apps (1/3)

1675112374.jpg
Mohamad Abuzaid
7 months ago
Security in Android App Development (1/3)

Security in Android App Development (1/3)

1675112374.jpg
Mohamad Abuzaid
7 months ago