Architecture-samples: [master] ServiceLocator.kt redundant code ?

Created on 24 Sep 2019  路  3Comments  路  Source: android/architecture-samples

In app/src/mock/java/com/example/android/architecture/blueprints/todoapp/ServiceLocator.kt锛孡43. Why repeat tasksRepository ?: in return?

Can the return be simplified as return tasksRepository ?: createTasksRepository(context) ?

    fun provideTasksRepository(context: Context): TasksRepository {
        synchronized(this) {
            return tasksRepository ?: tasksRepository ?: createTasksRepository(context) // HERE!
        }
    }

Thanks for your attention.

Most helpful comment

Actually, it's possible to make it work correctly:

    fun provideTasksRepository(context: Context): TasksRepository {
        return tasksRepository ?: synchronized(this) {
            tasksRepository ?: createTasksRepository(context)
        }
    }

I wouldn't say this improves readability though.

All 3 comments

I suppose that's an attempt to implement Double-check locking pattern in idiomatic Kotlin-style way. Unfortunately, it's implemented incorrectly since the first null check should be done outside of synchronized block - that's required to avoid synchronization when the property is inited. Otherwise, one of the null-checks is useless.

Actually, it's possible to make it work correctly:

    fun provideTasksRepository(context: Context): TasksRepository {
        return tasksRepository ?: synchronized(this) {
            tasksRepository ?: createTasksRepository(context)
        }
    }

I wouldn't say this improves readability though.

Also in this class, L68, in function resetRepository(), synchronization with lock instead of this may cause returning null in function provideTasksRepository(Context).

kotlin fun resetRepository() { synchronized(lock) { runBlocking { FakeTasksRemoteDataSource.deleteAllTasks() } // Clear all data to avoid test pollution. database?.apply { clearAllTables() close() } database = null tasksRepository = null } }

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iraj-wisilica picture iraj-wisilica  路  6Comments

aitorvs picture aitorvs  路  4Comments

nucle picture nucle  路  7Comments

jacquesgiraudel picture jacquesgiraudel  路  6Comments

bmomani1 picture bmomani1  路  4Comments